UNPKG

dejavu-call

Version:

Intercepts a function call and stores the result with the given context. In calls that have the same parameters, it will return the stored result. The proposal is to reduce the response time for processing heavy functions, but it always has the same resul

63 lines (48 loc) 1.82 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports._memorize = exports.stringify = exports.isEssential = undefined; var _pytils = require('pytils'); var _sha = require('./sha256'); var _sha2 = _interopRequireDefault(_sha); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var isEssential = exports.isEssential = function isEssential(Service, contextId, context) { (0, _pytils.ifThrow)(!(0, _pytils.isFunction)(Service), 'dejavu-call: Service is a essential! and need to be a function'); (0, _pytils.ifThrow)(!(0, _pytils.isString)(contextId), 'dejavu-call: contextId is a essential! and need to be a string'); (0, _pytils.ifThrow)(!(0, _pytils.isArray)(context), 'dejavu-call: context is a essential! and need to be a array'); }; var stringify = exports.stringify = function stringify(context) { return (0, _sha2.default)(JSON.stringify(context.map(function (param) { return (0, _pytils.type)(param) === 'function' ? param.toString() : param; }))); }; var createKeeper = function createKeeper() { return { first: 0, last: -1, count: -1, ref: {}, memo: {} }; }; var forget = function forget(keeper) { var first = keeper.first; var ref = keeper.ref[first]; delete keeper.memo[ref]; delete keeper.ref[first]; keeper.count -= 1; keeper.first += 1; }; var _memorize = exports._memorize = function _memorize(inMind, limit) { return function (contextId, contextString, result) { var keeper = inMind[contextId] ? inMind[contextId] : inMind[contextId] = createKeeper(); var last = keeper.last += 1; keeper.ref[last] = contextString; keeper.memo[contextString] = result; keeper.count += 1; if (keeper.count > limit) { forget(keeper); } }; };