forked from HowProgrammingWorks/Memoization
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-speed.js
More file actions
40 lines (31 loc) · 878 Bytes
/
2-speed.js
File metadata and controls
40 lines (31 loc) · 878 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
'use strict';
const argKey = x => x.toString() + ':' + typeof x;
const generateKey = args => args.map(argKey).join('|');
const memoize = fn => {
const cache = {};
return (...args) => {
const key = generateKey(args);
const val = cache[key];
if (val) return val;
const res = fn(...args);
cache[key] = res;
return res;
};
};
// Utils
const LOOP_COUNT = 10000;
const speedTest = (name, fn, args, count) => {
const tmp = [];
const start = new Date().getTime();
for (let i = 0; i < count; i++) {
tmp.push(fn(...args));
}
const end = new Date().getTime();
const time = end - start;
console.log(`${name} * ${tmp.length} : ${time}`);
};
// Usage
const fib = n => (n <= 2 ? 1 : fib(n - 1) + fib(n - 2));
speedTest('fib(20)', fib, [20], LOOP_COUNT);
const mFib = memoize(fib);
speedTest('memoized fib(20)', mFib, [20], LOOP_COUNT);