Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache function reference when it's a single argument #35

Merged
merged 13 commits into from
May 14, 2019
8 changes: 3 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,9 @@ const defaultCacheKey = (...arguments_) => {

if (arguments_.length === 1) {
const [firstArgument] = arguments_;
if (
firstArgument === null ||
firstArgument === undefined ||
(typeof firstArgument !== 'function' && typeof firstArgument !== 'object')
) {
const isObject = typeof firstArgument === 'object' && firstArgument !== null;
const isPrimitive = !isObject;
if (isPrimitive) {
return firstArgument;
}
}
Expand Down
2 changes: 1 addition & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

> [Memoize](https://en.wikipedia.org/wiki/Memoization) functions - An optimization used to speed up consecutive function calls by caching the result of calls with identical input

Memory is automatically released when an item expires.
The input is cached by value (if supported by `JSON.stringify`) unless it’s a single argument of type `function`, in which case it’s stored by reference. Memory is automatically released when an item expires.
fregante marked this conversation as resolved.
Show resolved Hide resolved


## Install
Expand Down
14 changes: 14 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,20 @@ test('memoize', t => {
t.is(memoized('foo', 'bar'), 2);
t.is(memoized('foo', 'bar'), 2);
t.is(memoized('foo', 'bar'), 2);
t.is(memoized(1), 3);
t.is(memoized(1), 3);
t.is(memoized(null), 4);
t.is(memoized(null), 4);
t.is(memoized(undefined), 5);
t.is(memoized(undefined), 5);
t.is(memoized(fixture), 6);
t.is(memoized(fixture), 6);
t.is(memoized(true), 7);
t.is(memoized(true), 7);

// Ensure that functions are stored by reference and not by "value" (e.g. their `.toString()` representation)
t.is(memoized(() => i++), 8);
t.is(memoized(() => i++), 9);
});

test('memoize with multiple non-primitive arguments', t => {
Expand Down