-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy path5-sha.js
More file actions
42 lines (32 loc) · 899 Bytes
/
5-sha.js
File metadata and controls
42 lines (32 loc) · 899 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
41
42
'use strict';
const crypto = require('node:crypto');
const argKey = (x) => x.toString() + ':' + typeof x;
const generateKey = (args) => {
const key = args.map(argKey).join('|');
return crypto.createHash('sha256').update(key).digest('hex');
};
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;
};
};
// Usage
const sumSeq = (a, b) => {
console.log('Calculate sum');
let r = 0;
for (let i = a; i < b; i++) r += i;
return r;
};
const mSumSeq = memoize(sumSeq);
console.log('First call mSumSeq(2, 5)');
console.log('Value:', mSumSeq(2, 5));
console.log('Second call mSumSeq(2, 5)');
console.log('From cache:', mSumSeq(2, 5));
console.log('Call mSumSeq(2, 6)');
console.log('Calculated:', mSumSeq(2, 6));