Skip to content

Commit

Permalink
Using for loop for improved speed (#59)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexreardon authored Apr 8, 2019
1 parent cbde410 commit dc00d09
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 14 deletions.
20 changes: 20 additions & 0 deletions src/are-inputs-equal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// @flow
export default function areInputsEqual(
newInputs: mixed[],
lastInputs: mixed[],
) {
// no checks needed if the inputs length has changed
if (newInputs.length !== lastInputs.length) {
return false;
}
// Using for loop for speed. It generally performs better than array.every
// https://github.com/alexreardon/memoize-one/pull/59

for (let i = 0; i < newInputs.length; i++) {
// using shallow equality check
if (newInputs[i] !== lastInputs[i]) {
return false;
}
}
return true;
}
17 changes: 3 additions & 14 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,7 @@
// @flow
export type EqualityFn = (newArgs: mixed[], lastArgs: mixed[]) => boolean;

const shallowEqual = (newValue: mixed, oldValue: mixed): boolean =>
newValue === oldValue;
import areInputsEqual from './are-inputs-equal';

const simpleIsEqual: EqualityFn = (
newArgs: mixed[],
lastArgs: mixed[],
): boolean =>
newArgs.length === lastArgs.length &&
newArgs.every(
(newArg: mixed, index: number): boolean =>
shallowEqual(newArg, lastArgs[index]),
);
export type EqualityFn = (newArgs: mixed[], lastArgs: mixed[]) => boolean;

// Type TArgs (arguments type) and TRet (return type) as generics to ensure that the
// returned function (`memoized`) has the same type as the provided function (`inputFn`).
Expand All @@ -22,7 +11,7 @@ const simpleIsEqual: EqualityFn = (
// See https://flow.org/en/docs/types/mixed/ for more.
export default function memoizeOne<TArgs: mixed[], TRet: mixed>(
inputFn: (...TArgs) => TRet,
isEqual?: EqualityFn = simpleIsEqual,
isEqual?: EqualityFn = areInputsEqual,
): (...TArgs) => TRet {
let lastThis: mixed;
let lastArgs: ?TArgs;
Expand Down

0 comments on commit dc00d09

Please sign in to comment.