@jsonjoy.com/json-type
Version:
High-performance JSON Pointer implementation
37 lines • 1.3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.lazyKeyedFactory = exports.normalizeAccessor = void 0;
const normalizeAccessor = (key) => {
// Simple property access for valid identifiers, bracket notation otherwise
if (/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(key)) {
return `.${key}`;
}
return `[${JSON.stringify(key)}]`;
};
exports.normalizeAccessor = normalizeAccessor;
/**
* Creates a lazily evaluated factory function that caches results based on the
* first argument.
*
* @param factory A factory function that takes a key as the first argument,
* potentially more arguments, and returns a function.
*/
const lazyKeyedFactory = (factory) => {
const cache = new WeakMap();
return function (...factoryArgs) {
const factoryThis = this;
const key = factoryArgs[0];
let estimator = cache.get(key);
if (estimator)
return estimator;
return function (...methodArgs) {
if (!estimator) {
estimator = factory.call(factoryThis, ...factoryArgs);
cache.set(key, estimator);
}
return estimator.call(this, ...methodArgs);
};
};
};
exports.lazyKeyedFactory = lazyKeyedFactory;
//# sourceMappingURL=util.js.map