Skip to content

Instantly share code, notes, and snippets.

@petsel
Created July 16, 2018 00:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save petsel/1266496dc838a1360dc74db21c1a8f34 to your computer and use it in GitHub Desktop.
Save petsel/1266496dc838a1360dc74db21c1a8f34 to your computer and use it in GitHub Desktop.
(function (global) {
'use strict';
var
Array = global.Array,
Object = global.Object,
RegExp = global.RegExp,
Function = global.Function,
array_from = Array.from,
object_prototype = Object.prototype,
function_prototype = Function.prototype,
TYPEOF_FUNCTION_TYPE = (typeof Function);
function isFunction(type) {
return ((typeof type === TYPEOF_FUNCTION_TYPE) && (typeof type.call === TYPEOF_FUNCTION_TYPE) && (typeof type.apply === TYPEOF_FUNCTION_TYPE));
}
function isValue(type) {
return RegExp('^\\[object\\s+Boolean|Number|String|Symbol\\]$').test(object_prototype.toString.call(type));
}
function isMemoLink(type) {
return (type instanceof MemoLink);
}
function MemoLink() {
return this;
}
function getSanitizedTarget(target) {
/* eslint-disable */
/* jshint ignore:start */
/* ignore jslint start */
/* no-eq-null */
return ((target != null) && target) || null;
/* ignore jslint end */
/* jshint ignore:end */
/* eslint-enable */
}
function createFunctionWithBoundMemoizationForValueBasedArgumentsOnly(target) {
var
nonmemoizingFct = this,
memoizerChain = (new MemoLink());
target = getSanitizedTarget(target);
function memoizeAndRecall(collector, argsValue, idx, argsArray) {
if ('memo' in collector) {
if (isValue(argsValue)) {
var
memo = collector.memo;
if (isMemoLink(memo[argsValue])) {
// recall.
collector.memo = memo[argsValue];
} else if (idx === (argsArray.length - 1)) {
if (argsValue in memo) {
// recall.
collector.memo = memo[argsValue];
} else {
// memoize.
collector.memo = memo[argsValue] = nonmemoizingFct.apply(collector.context, collector.args);
}
} else {
// keep recalling/memoizing.
collector.memo = memo[argsValue] = (new MemoLink());
}
} else {
delete collector.memo;
}
}
return collector;
}
function memoizingFct() {
var
context = (target || getSanitizedTarget(this)), // a memoized method's target can be delegated at call time but only if it was not provided at composition time.
args = arguments,
result = array_from(args).reduce(memoizeAndRecall, { memo: memoizerChain, args: args, context: context });
return (('memo' in result) ? result.memo : nonmemoizingFct.apply(context, args));
}
return ((isFunction(nonmemoizingFct) && memoizingFct) || nonmemoizingFct);
}
function_prototype.memoize = createFunctionWithBoundMemoizationForValueBasedArgumentsOnly;
}(window));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment