context
Version:
69 lines (65 loc) • 2.43 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('vest-utils')) :
typeof define === 'function' && define.amd ? define(['exports', 'vest-utils'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.context = {}, global["vest-utils"]));
})(this, (function (exports, vestUtils) { 'use strict';
const USEX_DEFAULT_ERROR_MESSAGE = 'Not inside of a running context.';
const EMPTY_CONTEXT = Symbol();
/**
* Base context interface.
*/
function createContext(defaultContextValue) {
let contextValue = EMPTY_CONTEXT;
return {
run,
use,
useX,
};
function use() {
return (isInsideContext() ? contextValue : defaultContextValue);
}
function useX(errorMessage) {
vestUtils.invariant(isInsideContext(), vestUtils.defaultTo(errorMessage, USEX_DEFAULT_ERROR_MESSAGE));
return contextValue;
}
function run(value, cb) {
const parentContext = isInsideContext() ? use() : EMPTY_CONTEXT;
contextValue = value;
const res = cb();
contextValue = parentContext;
return res;
}
function isInsideContext() {
return contextValue !== EMPTY_CONTEXT;
}
}
/**
* Cascading context - another implementation of context, that assumes the context value is an object.
* When nesting context runs, the the values of the current layer merges with the layers above it.
*/
function createCascade(init) {
const ctx = createContext();
return {
bind,
run,
use: ctx.use,
useX: ctx.useX,
};
function run(value, fn) {
var _a;
const parentContext = ctx.use();
const out = vestUtils.assign({}, parentContext ? parentContext : {}, (_a = vestUtils.optionalFunctionValue(init, value, parentContext)) !== null && _a !== void 0 ? _a : value);
return ctx.run(Object.freeze(out), fn);
}
function bind(value, fn) {
return function (...runTimeArgs) {
return run(value, function () {
return fn(...runTimeArgs);
});
};
}
}
exports.createCascade = createCascade;
exports.createContext = createContext;
}));
//# sourceMappingURL=context.development.js.map