Skip to content

Resolve

ixfx has a set of functions for ‘resolving’ something to a concrete value.

This can be useful for handling different kinds of input. Let’s say our function blah can process numbers:

/**
* @param {number} v
*/
function blah(v) {
if (typeof v !== `number`) throw new TypeError(`Param 'v' is not a number`);
return v*2;
}
blah(10);

But we also want it to accept numbers from asynchronous sources, generators, reactive and so on. Rather than writing all that code, Core.resolve can be used. Now our function can take all sorts of things that can eventually be resolved to a number.

import { resolve } from 'https://unpkg.com/@ixfx/core/bundle';
/**
* @param {ResolveToValue<number>} source
**/
function blah(source) {
const v = await resolve(source);
if (typeof v !== `number`) throw new TypeError(`Param 'source' did not resolve to a number`);
}
blah(10);
blah( () => 10); // ...etc

Core.resolveFields has the same logic as resolve, but it works across all the top-level properties of an object.

For example, let us say we have some state which is a combination of primitive data and functions which compute data dynamically:

const state = {
length: 10,
random: () => Math.random()
}
const use = () => {
const { length, random } = state;
// Need to compute function to get value
const randomValue = random();
console.log(`length: ${length} random: ${randomValue}`);
}
use();

Ideally the use function doesn’t need to care about how the data is being computed. But now we have to execute the random function and keep track of another variable. Instead Core.resolveFields can be used, which returns a plain object with plain values.

import { resolveFields } from 'https://unpkg.com/@ixfx/core/bundle';
const rawState = {
length: 10,
random: () => Math.random()
}
const use = async () => {
// We get back a plain object with plain values
const state = await resolveFields(rawState);
const { length, random } = state;
console.log(`length: ${length} random: ${random}`);
}
use();

Now our use function doesn’t need to care about how properties are being computed or if even if they are dynamic or not. We can swap length from being a number to a function and use doesn’t need to change.

resolve alternatives: