frontend/.pnpm-store/v3/files/76/96e88c52938333d3dbcbf40cf0ebe01d9b6beb41c715f9a3b64ba8890686e84f8bb069ff6da1bed15f757a0d326d6caf43008c539e4bab9ff7aaf9749d2a03-exec

79 lines
2.4 KiB
Plaintext
Executable File

//
// Main
//
export default function memoize(fn, options) {
var cache = options && options.cache ? options.cache : cacheDefault;
var serializer = options && options.serializer ? options.serializer : serializerDefault;
var strategy = options && options.strategy ? options.strategy : strategyDefault;
return strategy(fn, {
cache: cache,
serializer: serializer,
});
}
//
// Strategy
//
function isPrimitive(value) {
return (value == null || typeof value === 'number' || typeof value === 'boolean'); // || typeof value === "string" 'unsafe' primitive for our needs
}
function monadic(fn, cache, serializer, arg) {
var cacheKey = isPrimitive(arg) ? arg : serializer(arg);
var computedValue = cache.get(cacheKey);
if (typeof computedValue === 'undefined') {
computedValue = fn.call(this, arg);
cache.set(cacheKey, computedValue);
}
return computedValue;
}
function variadic(fn, cache, serializer) {
var args = Array.prototype.slice.call(arguments, 3);
var cacheKey = serializer(args);
var computedValue = cache.get(cacheKey);
if (typeof computedValue === 'undefined') {
computedValue = fn.apply(this, args);
cache.set(cacheKey, computedValue);
}
return computedValue;
}
function assemble(fn, context, strategy, cache, serialize) {
return strategy.bind(context, fn, cache, serialize);
}
function strategyDefault(fn, options) {
var strategy = fn.length === 1 ? monadic : variadic;
return assemble(fn, this, strategy, options.cache.create(), options.serializer);
}
function strategyVariadic(fn, options) {
return assemble(fn, this, variadic, options.cache.create(), options.serializer);
}
function strategyMonadic(fn, options) {
return assemble(fn, this, monadic, options.cache.create(), options.serializer);
}
//
// Serializer
//
var serializerDefault = function () {
return JSON.stringify(arguments);
};
//
// Cache
//
function ObjectWithoutPrototypeCache() {
this.cache = Object.create(null);
}
ObjectWithoutPrototypeCache.prototype.get = function (key) {
return this.cache[key];
};
ObjectWithoutPrototypeCache.prototype.set = function (key, value) {
this.cache[key] = value;
};
var cacheDefault = {
create: function create() {
// @ts-ignore
return new ObjectWithoutPrototypeCache();
},
};
export var strategies = {
variadic: strategyVariadic,
monadic: strategyMonadic,
};