Created
September 15, 2019 19:04
-
-
Save novonimo/8ad629b30101c17070274ffe6d71402e to your computer and use it in GitHub Desktop.
create a simple and fast memoization function for calculation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A note about immutable structure data in + immutable.js