Skip to content

Instantly share code, notes, and snippets.

@novonimo
Created September 15, 2019 19:04
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 novonimo/8ad629b30101c17070274ffe6d71402e to your computer and use it in GitHub Desktop.
Save novonimo/8ad629b30101c17070274ffe6d71402e to your computer and use it in GitHub Desktop.
create a simple and fast memoization function for calculation.
/*
use this memoiziation function with immutable js and see the
beautifulness of Js
calculate one time and use it every where
*/
function memoize(fn) {
let prevArg;
let prevResult;
return function (arg) {
return arg === prevArg
? prevResult
: (prevArg = arg, prevResult = fn.call(this, arg));
}
}
function sum(list) {
return list.reduce((a, b) => a + b);
}
let memoSum = memoize(sum);
let listOfOneBilionNumber = [...Array(1000000).keys()];
console.time("sum");
console.log(memoSum(listOfOneBilionNumber));
console.timeEnd("sum");
console.time("sum");
console.log(memoSum(listOfOneBilionNumber));
console.timeEnd("sum");
listOfOneBilionNumber.push(1001);
console.time("sum");
console.log(memoSum(listOfOneBilionNumber));
console.timeEnd("sum");
/*
because of we comapare arg === prevArg so when we add new item
to the array so the comparison will no sense to this change
so it return true and the function will not work correctly
*/
/*
import {List} from "immutable";
let list = List(listOfOneBilionNumbers)
*/
@novonimo
Copy link
Author

A note about immutable structure data in + immutable.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment