Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

micro-memoize

Package Overview
Dependencies
Maintainers
1
Versions
68
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

micro-memoize - npm Package Compare versions

Comparing version 2.1.2 to 3.0.0-beta.0

__tests__/index.ts

563

dist/micro-memoize.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
typeof define === 'function' && define.amd ? define(['exports'], factory) :
(factory((global.memoize = {})));
}(this, (function (exports) { 'use strict';
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global['micro-memoize'] = factory());
}(this, function () { 'use strict';
function _objectWithoutPropertiesLoose(source, excluded) {
if (source == null) return {};
var target = {};
var sourceKeys = Object.keys(source);
var key, i;
/*! *****************************************************************************
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
this file except in compliance with the License. You may obtain a copy of the
License at http://www.apache.org/licenses/LICENSE-2.0
for (i = 0; i < sourceKeys.length; i++) {
key = sourceKeys[i];
if (excluded.indexOf(key) >= 0) continue;
target[key] = source[key];
}
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
return target;
}
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
// types
var hasOwnProperty = Object.prototype.hasOwnProperty;
/**
* @function assign
*
* @description
* merge the sources into the target, as you would with Object.assign()
*
* @param {Object} target object to merge into
* @param {...Array<Object>} sources the sources to merge into the target
* @returns {Object} the merged object
*/
var assign = function assign(target) {
var source;
for (var index = 0; index < (arguments.length <= 1 ? 0 : arguments.length - 1); index++) {
source = index + 1 < 1 || arguments.length <= index + 1 ? undefined : arguments[index + 1];
if (source && typeof source === 'object') {
for (var key in source) {
if (hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
function __rest(s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
}
return target;
};
/**
* @function cloneArray
*
* @description
* clone the array-like object and return the new array
*
* @param {Array<any>|Arguments} arrayLike the array-like object to clone
* @returns {Array<any>} the clone of the array
*/
var cloneArray = function cloneArray(arrayLike) {
var length = arrayLike.length;
if (!length) {
return [];
function createAreKeysEqual(isEqual) {
/**
* @function areKeysEqual
*
* @description
* are the keys shallowly equal to one another
*
* @param key1 the keys array to test against
* @param key2 the keys array to test
* @returns are the keys shallowly equal
*/
return function areKeysEqual(key1, key2) {
var length = key1.length;
if (key2.length !== length) {
return false;
}
if (length === 1) {
return isEqual(key1[0], key2[0]);
}
var index = 0;
while (index < length) {
if (!isEqual(key1[index], key2[index])) {
return false;
}
index++;
}
return true;
};
}
if (length === 1) {
return [arrayLike[0]];
function createGetKeyIndex(options) {
var maxSize = options.maxSize;
var areKeysEqual = typeof options.isMatchingKey === 'function'
? options.isMatchingKey
: createAreKeysEqual(options.isEqual);
/**
* @function getKeyIndex
*
* @description
* get the index of the matching key
*
* @param allKeys the list of all available keys
* @param keyToMatch the key to try to match
*
* @returns {number} the index of the matching key value, or -1
*/
return function getKeyIndex(allKeys, keyToMatch) {
if (areKeysEqual(allKeys[0], keyToMatch)) {
return 0;
}
if (maxSize > 1) {
var length = maxSize > allKeys.length ? allKeys.length : maxSize;
var index = 1;
while (index < length) {
if (areKeysEqual(allKeys[index], keyToMatch)) {
return index;
}
index++;
}
}
return -1;
};
}
if (length === 2) {
return [arrayLike[0], arrayLike[1]];
/**
* @function isSameValueZero
*
* @description
* are the objects equal based on SameValueZero equality
*
* @param object1 the first object to compare
* @param object2 the second object to compare
* @returns are the two objects equal
*/
function isSameValueZero(object1, object2) {
return object1 === object2 || (object1 !== object1 && object2 !== object2);
}
if (length === 3) {
return [arrayLike[0], arrayLike[1], arrayLike[2]];
}
var array = new Array(length);
for (var index = 0; index < length; index++) {
array[index] = arrayLike[index];
}
return array;
};
var createAreKeysEqual = function createAreKeysEqual(isEqual
/**
* @function areKeysEqual
*
* @description
* are the keys shallowly equal to one another
*
* @param {Array<any>} keys1 the keys array to test against
* @param {Array<any>} keys2 the keys array to test
* @returns {boolean} are the keys shallowly equal
*/
) {
return function (keys1, keys2) {
if (keys1.length !== keys2.length) {
return false;
}
for (var index = 0, length = keys1.length; index < length; index++) {
if (!isEqual(keys1[index], keys2[index])) {
return false;
}
}
return true;
};
};
var createGetKeyIndex = function createGetKeyIndex(isEqual, isMatchingKey) {
var areKeysEqual = typeof isMatchingKey === 'function' ? isMatchingKey : createAreKeysEqual(isEqual);
/**
* @function getKeyIndex
* @function mergeOptions
*
* @description
* get the index of the matching key
* merge the options into the target
*
* @param {Array<Array<any>>} allKeys the list of all available keys
* @param {Array<any>} keysToMatch the key to try to match
*
* @returns {number} the index of the matching key value, or -1
* @param extraOptions the extra options passed
* @param providedOptions the defaulted options provided
* @returns the merged options
*/
return function (allKeys, keysToMatch) {
for (var index = 0; index < allKeys.length; index++) {
if (areKeysEqual(allKeys[index], keysToMatch)) {
return index;
function mergeOptions(extraOptions, providedOptions) {
var target = {};
for (var key in extraOptions) {
target[key] = extraOptions[key];
}
}
return -1;
};
};
/**
* @function isSameValueZero
*
* @description
* are the objects equal based on SameValueZero
*
* @param {any} object1 the first object to compare
* @param {any} object2 the second object to compare
* @returns {boolean} are the two objects equal
*/
var isSameValueZero = function isSameValueZero(object1, object2) {
return object1 === object2 || object1 !== object1 && object2 !== object2;
};
var onCacheOperation = function onCacheOperation(cacheIgnored, optionsIgnored, memoizedIgnored) {};
/**
* @function orderByLru
*
* @description
* order the array based on a Least-Recently-Used basis
*
* @param {Array<any>} array the array to order
* @param {any} value the value to assign at the beginning of the array
* @param {number} startingIndex the index of the item to move to the front
*/
var orderByLru = function orderByLru(array, value, startingIndex) {
var index = startingIndex;
while (index--) {
array[index + 1] = array[index];
}
array[0] = value;
};
/**
* @function createSetPromiseHandler
*
* @description
* update the promise method to auto-remove from cache if rejected, and if resolved then fire cache hit / changed
*
* @param {Options} options the options for the memoized function
* @param {function(Cache, function): function} memoized the memoized function
*/
var createSetPromiseHandler = function createSetPromiseHandler(options) {
var getKeyIndex = createGetKeyIndex(options.isEqual, options.isMatchingKey);
return function (cache, memoized) {
var key = cache.keys[0];
cache.values[0] = cache.values[0].then(function (value) {
options.onCacheHit(cache, options, memoized);
options.onCacheChange(cache, options, memoized);
return value;
}).catch(function (error) {
var keyIndex = getKeyIndex(cache.keys, key);
if (~keyIndex) {
cache.keys.splice(keyIndex, 1);
cache.values.splice(keyIndex, 1);
for (var key in providedOptions) {
target[key] = providedOptions[key];
}
throw error;
});
};
};
/**
* @function memoize
*
* @description
* get the memoized version of the method passed
*
* @param {function} fn the method to memoize
* @param {Object} [options={}] the options to build the memoizer with
* @param {boolean} [options.isEqual=isSameValueZero] the method to compare equality of keys with
* @param {number} [options.maxSize=1] the number of items to store in cache
* @returns {function} the memoized method
*/
function memoize(fn, options) {
// if it is a memoized method, don't re-memoize it
if (fn.isMemoized) {
return fn;
return target;
}
var _ref = options || {},
_ref$isEqual = _ref.isEqual,
isEqual = _ref$isEqual === void 0 ? isSameValueZero : _ref$isEqual,
isMatchingKey = _ref.isMatchingKey,
_ref$isPromise = _ref.isPromise,
isPromise = _ref$isPromise === void 0 ? false : _ref$isPromise,
_ref$maxSize = _ref.maxSize,
maxSize = _ref$maxSize === void 0 ? 1 : _ref$maxSize,
_ref$onCacheAdd = _ref.onCacheAdd,
onCacheAdd = _ref$onCacheAdd === void 0 ? onCacheOperation : _ref$onCacheAdd,
_ref$onCacheChange = _ref.onCacheChange,
onCacheChange = _ref$onCacheChange === void 0 ? onCacheOperation : _ref$onCacheChange,
_ref$onCacheHit = _ref.onCacheHit,
onCacheHit = _ref$onCacheHit === void 0 ? onCacheOperation : _ref$onCacheHit,
transformKey = _ref.transformKey,
extraOptions = _objectWithoutPropertiesLoose(_ref, ["isEqual", "isMatchingKey", "isPromise", "maxSize", "onCacheAdd", "onCacheChange", "onCacheHit", "transformKey"]);
var normalizedOptions = assign({}, extraOptions, {
isEqual: isEqual,
isMatchingKey: isMatchingKey,
isPromise: isPromise,
maxSize: maxSize,
onCacheAdd: onCacheAdd,
onCacheChange: onCacheChange,
onCacheHit: onCacheHit,
transformKey: transformKey
});
var getKeyIndex = createGetKeyIndex(isEqual, isMatchingKey);
var setPromiseHandler = createSetPromiseHandler(normalizedOptions);
var shouldCloneArguments = !!(transformKey || isMatchingKey);
var cache = {
keys: [],
get size() {
return cache.keys.length;
},
values: []
};
var keys = cache.keys,
values = cache.values;
/**
* @function memoized
* @function orderByLru
*
* @description
* the memoized version of the method passed
* order the array based on a Least-Recently-Used basis
*
* @param {...Array<any>} key the arguments passed, which create a unique cache key
* @returns {any} the value of the method called with the arguments
* @param keys the keys to order
* @param newKey the new key to move to the front
* @param values the values to order
* @param newValue the new value to move to the front
* @param startingIndex the index of the item to move to the front
*/
function memoized() {
var args = arguments;
var normalizedArgs = shouldCloneArguments ? cloneArray(args) : args;
var key = transformKey ? transformKey(normalizedArgs) : normalizedArgs;
var keyIndex = getKeyIndex(keys, key);
if (~keyIndex) {
onCacheHit(cache, normalizedOptions, memoized);
if (keyIndex) {
orderByLru(keys, keys[keyIndex], keyIndex);
orderByLru(values, values[keyIndex], keyIndex);
onCacheChange(cache, normalizedOptions, memoized);
function orderByLru(cache, newKey, newValue, startingIndex, maxSize) {
var index = startingIndex;
while (index--) {
cache.keys[index + 1] = cache.keys[index];
cache.values[index + 1] = cache.values[index];
}
} else {
if (keys.length >= maxSize) {
keys.pop();
values.pop();
cache.keys[0] = newKey;
cache.values[0] = newValue;
if (startingIndex >= maxSize) {
cache.keys.length = maxSize;
cache.values.length = maxSize;
}
var newKey = shouldCloneArguments ? key : cloneArray(normalizedArgs);
var newValue = fn.apply(this, args);
orderByLru(keys, newKey, keys.length);
orderByLru(values, newValue, values.length);
if (isPromise) {
setPromiseHandler(cache, memoized);
}
onCacheAdd(cache, normalizedOptions, memoized);
onCacheChange(cache, normalizedOptions, memoized);
}
return values[0];
}
function createUpdateAsyncCache(options) {
var getKeyIndex = createGetKeyIndex(options);
var onCacheChange = options.onCacheChange, onCacheHit = options.onCacheHit;
var shouldUpdateOnChange = typeof onCacheChange === 'function';
var shouldUpdateOnHit = typeof onCacheHit === 'function';
/**
* @function updateAsyncCache
*
* @description
* update the promise method to auto-remove from cache if rejected, and
* if resolved then fire cache hit / changed
*
* @param cache the memoized function's cache
* @param memoized the memoized function
*/
return function (cache, memoized) {
var key = cache.keys[0];
cache.values[0] = cache.values[0]
.then(function (value) {
shouldUpdateOnHit && onCacheHit(cache, options, memoized);
shouldUpdateOnChange && onCacheChange(cache, options, memoized);
return value;
})
.catch(function (error) {
var keyIndex = getKeyIndex(cache.keys, key);
if (~keyIndex) {
cache.keys.splice(keyIndex, 1);
cache.values.splice(keyIndex, 1);
}
throw error;
});
};
}
Object.defineProperties(memoized, {
cache: {
configurable: true,
get: function get() {
return cache;
var slice = Array.prototype.slice;
function createMemoizedFunction(fn, options) {
if (options === void 0) { options = {}; }
// @ts-ignore
if (fn.isMemoized) {
return fn;
}
},
cacheSnapshot: {
configurable: true,
get: function get() {
return {
keys: cloneArray(cache.keys),
size: cache.size,
values: cloneArray(cache.values)
};
var _a = options.isEqual, isEqual = _a === void 0 ? isSameValueZero : _a, isMatchingKey = options.isMatchingKey, _b = options.isPromise, isPromise = _b === void 0 ? false : _b, _c = options.maxSize, maxSize = _c === void 0 ? 1 : _c, onCacheAdd = options.onCacheAdd, onCacheChange = options.onCacheChange, onCacheHit = options.onCacheHit, transformKey = options.transformKey, extraOptions = __rest(options, ["isEqual", "isMatchingKey", "isPromise", "maxSize", "onCacheAdd", "onCacheChange", "onCacheHit", "transformKey"]);
var normalizedOptions = mergeOptions(extraOptions, {
isEqual: isEqual,
isMatchingKey: isMatchingKey,
isPromise: isPromise,
maxSize: maxSize,
onCacheAdd: onCacheAdd,
onCacheChange: onCacheChange,
onCacheHit: onCacheHit,
transformKey: transformKey,
});
var getKeyIndex = createGetKeyIndex(normalizedOptions);
var updateAsyncCache = createUpdateAsyncCache(normalizedOptions);
var keys = [];
var values = [];
var cache = {
keys: keys,
get size() {
return cache.keys.length;
},
values: values,
};
var canTransformKey = typeof transformKey === 'function';
var shouldCloneArguments = !!(transformKey || isMatchingKey);
var shouldUpdateOnAdd = typeof onCacheAdd === 'function';
var shouldUpdateOnChange = typeof onCacheChange === 'function';
var shouldUpdateOnHit = typeof onCacheHit === 'function';
function memoized() {
var normalizedArgs = shouldCloneArguments
? slice.call(arguments, 0)
: arguments;
var key = canTransformKey
? transformKey(normalizedArgs)
: normalizedArgs;
var keyIndex = keys.length ? getKeyIndex(keys, key) : -1;
if (~keyIndex) {
shouldUpdateOnHit && onCacheHit(cache, normalizedOptions, memoized);
if (keyIndex) {
orderByLru(cache, keys[keyIndex], values[keyIndex], keyIndex, maxSize);
shouldUpdateOnChange &&
onCacheChange(cache, normalizedOptions, memoized);
}
}
else {
var newValue = fn.apply(this, arguments);
var newKey = shouldCloneArguments
? key
: slice.call(normalizedArgs, 0);
orderByLru(cache, newKey, newValue, keys.length, maxSize);
isPromise && updateAsyncCache(cache, memoized);
shouldUpdateOnAdd && onCacheAdd(cache, normalizedOptions, memoized);
shouldUpdateOnChange && onCacheChange(cache, normalizedOptions, memoized);
}
return values[0];
}
},
isMemoized: {
configurable: true,
get: function get() {
return true;
}
},
options: {
configurable: true,
get: function get() {
return normalizedOptions;
}
}
});
return memoized;
}
Object.defineProperties(memoized, {
cache: {
configurable: true,
value: cache,
},
cacheSnapshot: {
configurable: true,
get: function () {
return {
keys: slice.call(cache.keys, 0),
size: cache.size,
values: slice.call(cache.values, 0),
};
},
},
isMemoized: {
configurable: true,
value: true,
},
options: {
configurable: true,
value: normalizedOptions,
},
});
return memoized;
}
exports.default = memoize;
return createMemoizedFunction;
Object.defineProperty(exports, '__esModule', { value: true });
})));
}));
//# sourceMappingURL=micro-memoize.js.map

@@ -1,1 +0,1 @@

!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n(exports):"function"==typeof define&&define.amd?define(["exports"],n):n(e.memoize={})}(this,function(e){"use strict";var O=Object.prototype.hasOwnProperty,P=function(e){var n=e.length;if(!n)return[];if(1===n)return[e[0]];if(2===n)return[e[0],e[1]];if(3===n)return[e[0],e[1],e[2]];for(var t=new Array(n),r=0;r<n;r++)t[r]=e[r];return t},q=function(e,n){var i,r="function"==typeof n?n:(i=e,function(e,n){if(e.length!==n.length)return!1;for(var t=0,r=e.length;t<r;t++)if(!i(e[t],n[t]))return!1;return!0});return function(e,n){for(var t=0;t<e.length;t++)if(r(e[t],n))return t;return-1}},A=function(e,n){return e===n||e!=e&&n!=n},E=function(e,n,t){},H=function(e,n,t){for(var r=t;r--;)e[r+1]=e[r];e[0]=n};e.default=function(u,e){if(u.isMemoized)return u;var i,o,n=e||{},t=n.isEqual,r=void 0===t?A:t,a=n.isMatchingKey,f=n.isPromise,c=void 0!==f&&f,s=n.maxSize,h=void 0===s?1:s,l=n.onCacheAdd,g=void 0===l?E:l,v=n.onCacheChange,d=void 0===v?E:v,y=n.onCacheHit,p=void 0===y?E:y,m=n.transformKey,C=function(e){for(var n,t=0;t<(arguments.length<=1?0:arguments.length-1);t++)if((n=t+1<1||arguments.length<=t+1?void 0:arguments[t+1])&&"object"==typeof n)for(var r in n)O.call(n,r)&&(e[r]=n[r]);return e}({},function(e,n){if(null==e)return{};var t,r,i={},o=Object.keys(e);for(r=0;r<o.length;r++)t=o[r],0<=n.indexOf(t)||(i[t]=e[t]);return i}(n,["isEqual","isMatchingKey","isPromise","maxSize","onCacheAdd","onCacheChange","onCacheHit","transformKey"]),{isEqual:r,isMatchingKey:a,isPromise:c,maxSize:h,onCacheAdd:g,onCacheChange:d,onCacheHit:p,transformKey:m}),b=q(r,a),k=(o=q((i=C).isEqual,i.isMatchingKey),function(t,n){var r=t.keys[0];t.values[0]=t.values[0].then(function(e){return i.onCacheHit(t,i,n),i.onCacheChange(t,i,n),e}).catch(function(e){var n=o(t.keys,r);throw~n&&(t.keys.splice(n,1),t.values.splice(n,1)),e})}),z=!(!m&&!a),x={keys:[],get size(){return x.keys.length},values:[]},K=x.keys,M=x.values;function j(){var e=arguments,n=z?P(e):e,t=m?m(n):n,r=b(K,t);if(~r)p(x,C,j),r&&(H(K,K[r],r),H(M,M[r],r),d(x,C,j));else{K.length>=h&&(K.pop(),M.pop());var i=z?t:P(n),o=u.apply(this,e);H(K,i,K.length),H(M,o,M.length),c&&k(x,j),g(x,C,j),d(x,C,j)}return M[0]}return Object.defineProperties(j,{cache:{configurable:!0,get:function(){return x}},cacheSnapshot:{configurable:!0,get:function(){return{keys:P(x.keys),size:x.size,values:P(x.values)}}},isMemoized:{configurable:!0,get:function(){return!0}},options:{configurable:!0,get:function(){return C}}}),j},Object.defineProperty(e,"__esModule",{value:!0})});
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e=e||self)["micro-memoize"]=n()}(this,function(){"use strict";function w(e){var o,r=e.maxSize,a="function"==typeof e.isMatchingKey?e.isMatchingKey:(o=e.isEqual,function(e,n){var t=e.length;if(n.length!==t)return!1;if(1===t)return o(e[0],n[0]);for(var i=0;i<t;){if(!o(e[i],n[i]))return!1;i++}return!0});return function(e,n){if(a(e[0],n))return 0;if(1<r)for(var t=r>e.length?e.length:r,i=1;i<t;){if(a(e[i],n))return i;i++}return-1}}function A(e,n){return e===n||e!=e&&n!=n}function E(e,n,t,i,o){for(var r=i;r--;)e.keys[r+1]=e.keys[r],e.values[r+1]=e.values[r];e.keys[0]=n,e.values[0]=t,o<=i&&(e.keys.length=o,e.values.length=o)}var H=Array.prototype.slice;return function(r,e){if(void 0===e&&(e={}),r.isMemoized)return r;var o,a,u,f,c,s,n=e.isEqual,t=void 0===n?A:n,i=e.isMatchingKey,l=e.isPromise,h=void 0!==l&&l,y=e.maxSize,v=void 0===y?1:y,g=e.onCacheAdd,p=e.onCacheChange,d=e.onCacheHit,m=e.transformKey,C=function(e,n){var t={};for(var i in e)t[i]=e[i];for(var i in n)t[i]=n[i];return t}(function(e,n){var t={};for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&n.indexOf(i)<0&&(t[i]=e[i]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(i=Object.getOwnPropertySymbols(e);o<i.length;o++)n.indexOf(i[o])<0&&(t[i[o]]=e[i[o]])}return t}(e,["isEqual","isMatchingKey","isPromise","maxSize","onCacheAdd","onCacheChange","onCacheHit","transformKey"]),{isEqual:t,isMatchingKey:i,isPromise:h,maxSize:v,onCacheAdd:g,onCacheChange:p,onCacheHit:d,transformKey:m}),b=w(C),k=(a=w(o=C),u=o.onCacheChange,f=o.onCacheHit,c="function"==typeof u,s="function"==typeof f,function(t,n){var i=t.keys[0];t.values[0]=t.values[0].then(function(e){return s&&f(t,o,n),c&&u(t,o,n),e}).catch(function(e){var n=a(t.keys,i);throw~n&&(t.keys.splice(n,1),t.values.splice(n,1)),e})}),z=[],O=[],x={keys:z,get size(){return x.keys.length},values:O},K="function"==typeof m,M=!(!m&&!i),P="function"==typeof g,S="function"==typeof p,j="function"==typeof d;function q(){var e=M?H.call(arguments,0):arguments,n=K?m(e):e,t=z.length?b(z,n):-1;if(~t)j&&d(x,C,q),t&&(E(x,z[t],O[t],t,v),S&&p(x,C,q));else{var i=r.apply(this,arguments),o=M?n:H.call(e,0);E(x,o,i,z.length,v),h&&k(x,q),P&&g(x,C,q),S&&p(x,C,q)}return O[0]}return Object.defineProperties(q,{cache:{configurable:!0,value:x},cacheSnapshot:{configurable:!0,get:function(){return{keys:H.call(x.keys,0),size:x.size,values:H.call(x.values,0)}}},isMemoized:{configurable:!0,value:!0},options:{configurable:!0,value:C}}),q}});

@@ -1,14 +0,21 @@

const fs = require('fs-extra');
const fs = require('fs');
const path = require('path');
const ES_DIRECTORY = path.join(__dirname, 'es');
const MJS_DIRECTORY = path.join(__dirname, 'mjs');
const pkg = require('./package.json');
fs.readdirSync(ES_DIRECTORY).forEach((file) => {
const fullPathJsFilename = path.resolve(ES_DIRECTORY, file);
const fullPathMjsFilename = path.resolve(MJS_DIRECTORY, `${file.slice(0, -3)}.mjs`);
const SOURCE = path.join(__dirname, pkg.module);
const DESTINATION = path.join(__dirname, pkg.module.replace('esm.js', 'mjs'));
fs.copySync(fullPathJsFilename, fullPathMjsFilename);
const getFileName = filename => {
const split = filename.split('/');
console.log(`es/${file} -> mjs/${file.slice(0, -3)}.mjs`);
return split[split.length - 1];
};
fs.copyFile(SOURCE, DESTINATION, error => {
if (error) {
throw error;
}
console.log(`Copied ${getFileName(SOURCE)} to ${getFileName(DESTINATION)}`);
});

@@ -1,20 +0,60 @@

interface Cache {
keys: Array<any>;
size: number;
values: Array<any>;
}
type PlainObject = {
[key: string]: any;
[index: number]: any;
};
interface Options {
isEqual?: (firstValue: any, secondValue: any) => boolean;
isMatchingKey?: (cacheKey: Array<any>, key: Array<any>) => boolean;
isPromise?: boolean;
maxSize?: number;
onCacheAdd?: (cache: Cache, options: Options, memoized: Function) => void;
onCacheChange?: (cache: Cache, options: Options, memoized: Function) => void;
onCacheHit?: (cache: Cache, options: Options, memoized: Function) => void;
transformKey?: (args: any[]) => any;
declare namespace MicroMemoize {
export type Key = any[];
export type RawKey = Key | IArguments;
export type Keys = Key[];
export type Values = any[];
export type Cache = {
keys: Keys;
size: number;
values: Values;
};
export type EqualityComparator = (object1: any, object2: any) => boolean;
export type MatchingKeyComparator = (key1: Key, key2: RawKey) => boolean;
export type CacheModifiedHandler = (
cache: Cache,
options: Options,
memoized: Function,
) => void;
export type KeyTransformer = (args: RawKey) => Key;
export type KeyIndexGetter = (allKeys: Keys, keyToMatch: RawKey) => number;
export type AsyncCacheUpdater = (cache: Cache, memoized: Memoized) => void;
export type Options = {
isEqual?: EqualityComparator;
isMatchingKey?: MatchingKeyComparator;
isPromise?: boolean;
maxSize?: number;
onCacheAdd?: CacheModifiedHandler;
onCacheChange?: CacheModifiedHandler;
onCacheHit?: CacheModifiedHandler;
transformKey?: KeyTransformer;
};
export interface Memoized extends Function {
[key: string]: any;
cache?: Cache;
cacheSnapshot?: Cache;
isMemoized?: boolean;
options?: Options;
}
}
type Fn = (...args: any[]) => any;
export default function memoize<T extends Fn>(fn: T, options?: Options): T;
export default function memoize<T extends Function>(
fn: T,
options?: MicroMemoize.Options,
): MicroMemoize.Memoized;
{
"author": "tony.quetano@planttheidea.com",
"ava": {
"failFast": true,
"files": [
"test/*.js"
],
"require": [
"@babel/register"
],
"sources": [
"src/*.js"
],
"verbose": true
},
"browser": "dist/micro-memoize.js",
"browserslist": [

@@ -29,48 +17,35 @@ "defaults",

"devDependencies": {
"@babel/cli": "^7.1.2",
"@babel/core": "^7.1.2",
"@babel/plugin-syntax-flow": "^7.0.0",
"@babel/plugin-transform-flow-strip-types": "^7.0.0",
"@babel/plugin-transform-runtime": "^7.0.0",
"@babel/preset-env": "^7.0.0",
"@babel/preset-flow": "^7.0.0",
"@babel/preset-react": "^7.0.0",
"@babel/register": "^7.0.0",
"@babel/runtime": "^7.1.2",
"ava": "^1.0.0-rc.1",
"babel-eslint": "^10.0.1",
"babel-loader": "^8.0.4",
"@types/bluebird": "^3.5.25",
"@types/jest": "^24.0.0",
"@types/react": "^16.7.20",
"benchee": "^1.0.0",
"benchmark": "^2.1.4",
"case-sensitive-paths-webpack-plugin": "^2.1.2",
"bluebird": "^3.5.2",
"cli-table2": "^0.2.0",
"eslint": "^5.7.0",
"eslint-config-rapid7": "^3.0.4",
"eslint-friendly-formatter": "^4.0.1",
"eslint-loader": "^2.1.1",
"fast-equals": "^1.6.1",
"fast-memoize": "^2.5.1",
"flow-babel-webpack-plugin": "^1.1.1",
"fs-extra": "^7.0.0",
"hash-it": "^4.0.3",
"html-webpack-plugin": "^3.2.0",
"in-publish": "^2.0.0",
"lodash": "^4.17.10",
"jest": "^24.1.0",
"lodash": "^4.17.11",
"lru-memoize": "^1.0.2",
"mem": "^4.0.0",
"memoizee": "^0.4.13",
"memoizee": "^0.4.14",
"memoizerific": "^1.11.3",
"nyc": "^13.1.0",
"optimize-js-plugin": "^0.0.4",
"mini-bench": "^1.0.0",
"ora": "^3.0.0",
"prop-types": "^15.6.2",
"ramda": "^0.25.0",
"react": "^16.4.2",
"react-dev-utils": "^6.0.5",
"react-dom": "^16.4.2",
"react-hot-loader": "^4.3.11",
"rimraf": "^2.6.2",
"rollup": "^0.66.6",
"rollup-plugin-babel": "^4.0.1",
"performance-now": "^2.1.0",
"ramda": "^0.26.1",
"react": "^16.7.0",
"rollup": "^1.1.2",
"rollup-plugin-typescript": "^1.0.0",
"rollup-plugin-uglify": "^6.0.0",
"sinon": "^7.0.0",
"rsvp": "^4.8.4",
"simple-statistics": "^7.0.0",
"ts-jest": "^23.10.4",
"ts-loader": "^5.2.2",
"tslint": "^5.11.0",
"tslint-config-airbnb": "^5.11.0",
"tslint-loader": "^3.5.4",
"typescript": "^3.1.3",
"underscore": "^1.9.1",

@@ -100,4 +75,4 @@ "webpack": "^4.20.2",

"license": "MIT",
"main": "lib/index.js",
"module": "es/index.js",
"main": "dist/micro-memoize.cjs.js",
"module": "dist/micro-memoize.esm.js",
"name": "micro-memoize",

@@ -109,23 +84,20 @@ "repository": {

"scripts": {
"benchmark": "npm run transpile:lib -- --no-comments && node benchmark/index.js",
"benchmark:trace": "npm run transpile:lib -- --no-comments && node --trace-deopt --trace-opt benchmark/trace-test.js",
"benchmark:alternative": "npm run transpile:lib -- --no-comments && ALTERNATIVE=true node benchmark/index.js",
"benchmark": "npm run dist && NODE_ENV=production node ./benchmarks/index.js",
"build": "NODE_ENV=production rollup -c",
"clean": "rimraf lib && rimraf es && rimraf mjs && rimraf dist",
"copy:mjs": "node ./es-to-mjs.js",
"dev": "NODE_ENV=development webpack-dev-server --progress --colors --config=webpack/webpack.config.js",
"flow": "flow check src",
"lint": "eslint --max-warnings 0 src",
"build:mjs": "node ./es-to-mjs.js",
"clean": "rimraf dist",
"dev": "NODE_ENV=development webpack-dev-server --colors --progress --config=webpack/webpack.config.js",
"dist": "npm run clean && npm run build && npm run build:mjs",
"lint": "NODE_ENV=test tslint 'src/*.ts'",
"lint:fix": "npm run lint -- --fix",
"prepublish": "if in-publish; then npm run prepublish:compile; fi",
"prepublish:compile": "npm run lint && npm run flow && npm run test:coverage && npm run clean && npm run transpile:lib && npm run transpile:es && npm run copy:mjs && npm run build",
"prepublish:compile": "npm run lint && npm run test:coverage && npm run dist",
"start": "npm run dev",
"test": "NODE_PATH=. NODE_ENV=test ava",
"test:coverage": "nyc --cache npm test",
"test:watch": "npm run test -- --watch",
"transpile:es": "BABEL_ENV=es babel src --out-dir es",
"transpile:lib": "BABEL_ENV=lib babel src --out-dir lib"
"test": "NODE_PATH=. jest",
"test:coverage": "npm run test -- --coverage",
"test:watch": "npm run test -- --watch"
},
"sideEffects": false,
"types": "./index.d.ts",
"version": "2.1.2"
"version": "3.0.0-beta.0"
}

@@ -35,3 +35,3 @@ # micro-memoize

As the author of [`moize`](https://github.com/planttheidea/moize), I created a consistently fast memoization library, but `moize` has a lot of features to satisfy a large number of edge cases. `micro-memoize` is a simpler approach, focusing on the core feature set with a much smaller footprint (~1.1kB minified+gzipped). Stripping out these edge cases also allows `micro-memoize` to be faster across the board than `moize`.
As the author of [`moize`](https://github.com/planttheidea/moize), I created a consistently fast memoization library, but `moize` has a lot of features to satisfy a large number of edge cases. `micro-memoize` is a simpler approach, focusing on the core feature set with a much smaller footprint (~1.2kB minified+gzipped). Stripping out these edge cases also allows `micro-memoize` to be faster across the board than `moize`.

@@ -43,3 +43,3 @@ ## Importing

```javascript
import memoize from "micro-memoize";
import memoize from 'micro-memoize';
```

@@ -50,3 +50,3 @@

```javascript
import memoize from "micro-memoize/mjs";
import memoize from 'micro-memoize/mjs';
```

@@ -57,3 +57,3 @@

```javascript
const memoize = require("micro-memoize").default;
const memoize = require('micro-memoize').default;
```

@@ -65,6 +65,6 @@

// ES2015+
import memoize from "micro-memoize";
import memoize from 'micro-memoize';
// CommonJS
const memoize = require("micro-memoize").default;
const memoize = require('micro-memoize').default;

@@ -80,4 +80,4 @@ // old-school

console.log(memoized("one", "two")); // {one: 'one', two: 'two'}
console.log(memoized("one", "two")); // pulled from cache, {one: 'one', two: 'two'}
console.log(memoized('one', 'two')); // {one: 'one', two: 'two'}
console.log(memoized('one', 'two')); // pulled from cache, {one: 'one', two: 'two'}
```

@@ -99,3 +99,3 @@

```javascript
import { deepEqual } from "fast-equals";
import { deepEqual } from 'fast-equals';

@@ -105,3 +105,3 @@ const deepObject = object => {

foo: object.foo,
bar: object.bar
bar: object.bar,
};

@@ -115,11 +115,11 @@ };

foo: {
deep: "foo"
deep: 'foo',
},
bar: {
deep: "bar"
deep: 'bar',
},
baz: {
deep: "baz"
}
})
deep: 'baz',
},
}),
); // {foo: {deep: 'foo'}, bar: {deep: 'bar'}}

@@ -130,11 +130,11 @@

foo: {
deep: "foo"
deep: 'foo',
},
bar: {
deep: "bar"
deep: 'bar',
},
baz: {
deep: "baz"
}
})
deep: 'baz',
},
}),
); // pulled from cache

@@ -158,3 +158,3 @@ ```

```javascript
import { deepEqual } from "fast-equals";
import { deepEqual } from 'fast-equals';

@@ -164,3 +164,3 @@ const deepObject = object => {

foo: object.foo,
bar: object.bar
bar: object.bar,
};

@@ -172,7 +172,7 @@ };

return (
object1.hasOwnProperty("foo") &&
object2.hasOwnProperty("foo") &&
object1.hasOwnProperty('foo') &&
object2.hasOwnProperty('foo') &&
object1.bar === object2.bar
);
}
},
});

@@ -182,6 +182,6 @@

memoizedShape({
foo: "foo",
bar: "bar",
baz: "baz"
})
foo: 'foo',
bar: 'bar',
baz: 'baz',
}),
); // {foo: {deep: 'foo'}, bar: {deep: 'bar'}}

@@ -191,6 +191,6 @@

memoizedShape({
foo: "not foo",
bar: "bar",
baz: "baz"
})
foo: 'not foo',
bar: 'bar',
baz: 'baz',
}),
); // pulled from cache

@@ -219,3 +219,3 @@ ```

memoized("one", "two");
memoized('one', 'two');

@@ -246,11 +246,11 @@ console.log(memoized.cacheSnapshot.keys); // [['one', 'two']]

console.log(memoized("one", "two")); // ['one', 'two']
console.log(memoized("two", "three")); // ['two', 'three']
console.log(memoized("three", "four")); // ['three', 'four']
console.log(memoized('one', 'two')); // ['one', 'two']
console.log(memoized('two', 'three')); // ['two', 'three']
console.log(memoized('three', 'four')); // ['three', 'four']
console.log(memoized("one", "two")); // pulled from cache
console.log(memoized("two", "three")); // pulled from cache
console.log(memoized("three", "four")); // pulled from cache
console.log(memoized('one', 'two')); // pulled from cache
console.log(memoized('two', 'three')); // pulled from cache
console.log(memoized('three', 'four')); // pulled from cache
console.log(memoized("four", "five")); // ['four', 'five'], drops ['one', 'two'] from cache
console.log(memoized('four', 'five')); // ['four', 'five'], drops ['one', 'two'] from cache
```

@@ -273,18 +273,18 @@

onCacheAdd(cache, options) {
console.log("cache has been added to: ", cache);
console.log("memoized method has the following options applied: ", options);
}
console.log('cache has been added to: ', cache);
console.log('memoized method has the following options applied: ', options);
},
});
memoized("foo", "bar"); // cache has been added to
memoized("foo", "bar");
memoized("foo", "bar");
memoized('foo', 'bar'); // cache has been added to
memoized('foo', 'bar');
memoized('foo', 'bar');
memoized("bar", "foo"); // cache has been added to
memoized("bar", "foo");
memoized("bar", "foo");
memoized('bar', 'foo'); // cache has been added to
memoized('bar', 'foo');
memoized('bar', 'foo');
memoized("foo", "bar");
memoized("foo", "bar");
memoized("foo", "bar");
memoized('foo', 'bar');
memoized('foo', 'bar');
memoized('foo', 'bar');
```

@@ -307,18 +307,18 @@

onCacheChange(cache, options) {
console.log("cache has changed: ", cache);
console.log("memoized method has the following options applied: ", options);
}
console.log('cache has changed: ', cache);
console.log('memoized method has the following options applied: ', options);
},
});
memoized("foo", "bar"); // cache has changed
memoized("foo", "bar");
memoized("foo", "bar");
memoized('foo', 'bar'); // cache has changed
memoized('foo', 'bar');
memoized('foo', 'bar');
memoized("bar", "foo"); // cache has changed
memoized("bar", "foo");
memoized("bar", "foo");
memoized('bar', 'foo'); // cache has changed
memoized('bar', 'foo');
memoized('bar', 'foo');
memoized("foo", "bar"); // cache has changed
memoized("foo", "bar");
memoized("foo", "bar");
memoized('foo', 'bar'); // cache has changed
memoized('foo', 'bar');
memoized('foo', 'bar');
```

@@ -342,18 +342,18 @@

onCacheHit(cache, options) {
console.log("cache was hit: ", cache);
console.log("memoized method has the following options applied: ", options);
}
console.log('cache was hit: ', cache);
console.log('memoized method has the following options applied: ', options);
},
});
memoized("foo", "bar");
memoized("foo", "bar"); // cache was hit
memoized("foo", "bar"); // cache was hit
memoized('foo', 'bar');
memoized('foo', 'bar'); // cache was hit
memoized('foo', 'bar'); // cache was hit
memoized("bar", "foo");
memoized("bar", "foo"); // cache was hit
memoized("bar", "foo"); // cache was hit
memoized('bar', 'foo');
memoized('bar', 'foo'); // cache was hit
memoized('bar', 'foo'); // cache was hit
memoized("foo", "bar"); // cache was hit
memoized("foo", "bar"); // cache was hit
memoized("foo", "bar"); // cache was hit
memoized('foo', 'bar'); // cache was hit
memoized('foo', 'bar'); // cache was hit
memoized('foo', 'bar'); // cache was hit
```

@@ -375,7 +375,7 @@

const memoized = memoize(ignoreFunctionArgs, {
transformKey: JSON.stringify
transformKey: JSON.stringify,
});
console.log(memoized("one", () => {})); // ['one', () => {}]
console.log(memoized("one", () => {})); // pulled from cache, ['one', () => {}]
console.log(memoized('one', () => {})); // ['one', () => {}]
console.log(memoized('one', () => {})); // pulled from cache, ['one', () => {}]
```

@@ -396,9 +396,9 @@

return {
args: JSON.stringify(args)
args: JSON.stringify(args),
};
}
},
});
console.log(memoized("one", () => {})); // ['one', () => {}]
console.log(memoized("one", () => {})); // pulled from cache, ['one', () => {}]
console.log(memoized('one', () => {})); // ['one', () => {}]
console.log(memoized('one', () => {})); // pulled from cache, ['one', () => {}]
```

@@ -430,6 +430,6 @@

memoized.cache.keys.push(["one", "two"]);
memoized.cache.values.push("cached");
memoized.cache.keys.push(['one', 'two']);
memoized.cache.values.push('cached');
console.log(memoized("one", "two")); // 'cached'
console.log(memoized('one', 'two')); // 'cached'
```

@@ -436,0 +436,0 @@

@@ -1,35 +0,43 @@

import babel from 'rollup-plugin-babel';
import {uglify} from 'rollup-plugin-uglify';
import typescript from 'rollup-plugin-typescript';
import { uglify } from 'rollup-plugin-uglify';
export default [
{
input: 'src/index.js',
output: {
exports: 'named',
file: 'dist/micro-memoize.js',
format: 'umd',
name: 'memoize',
sourcemap: true,
},
plugins: [
babel({
exclude: 'node_modules/**',
}),
],
import pkg from './package.json';
const UMD_CONFIG = {
input: 'src/index.ts',
output: {
exports: 'default',
file: pkg.browser,
format: 'umd',
name: pkg.name,
sourcemap: true,
},
{
input: 'src/index.js',
output: {
exports: 'named',
file: 'dist/micro-memoize.min.js',
format: 'umd',
name: 'memoize',
},
plugins: [
babel({
exclude: 'node_modules/**',
}),
uglify(),
],
},
];
plugins: [
typescript({
typescript: require('typescript'),
}),
],
};
const FORMATTED_CONFIG = Object.assign({}, UMD_CONFIG, {
output: [
Object.assign({}, UMD_CONFIG.output, {
file: pkg.main,
format: 'cjs',
}),
Object.assign({}, UMD_CONFIG.output, {
file: pkg.module,
format: 'es',
}),
],
});
const MINIFIED_CONFIG = Object.assign({}, UMD_CONFIG, {
output: Object.assign({}, UMD_CONFIG.output, {
file: pkg.browser.replace('.js', '.min.js'),
sourcemap: false,
}),
plugins: UMD_CONFIG.plugins.concat([uglify()]),
});
export default [UMD_CONFIG, FORMATTED_CONFIG, MINIFIED_CONFIG];

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc