Skip to content

Commit 50448c6

Browse files
committed
Add exaple with sha-256 hash
1 parent 0eeda4c commit 50448c6

1 file changed

Lines changed: 38 additions & 0 deletions

File tree

JavaScript/5-sha.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
'use strict';
2+
3+
const crypto = require('crypto');
4+
5+
const generateKey = args => {
6+
const key = args.map(x => x.toString() + ':' + typeof(x)).join('|');
7+
return crypto.createHash('sha256').update(key).digest('hex');
8+
};
9+
10+
const memoize = fn => {
11+
const cache = {};
12+
return (...args) => {
13+
const key = generateKey(args);
14+
const val = cache[key];
15+
if (val) return val;
16+
const res = fn(...args);
17+
cache[key] = res;
18+
return res;
19+
};
20+
};
21+
22+
// Usage
23+
24+
const sumSeq = (a, b) => {
25+
console.log('Calculate sum');
26+
let r = 0;
27+
for (let i = a; i < b; i++) r += i;
28+
return r;
29+
};
30+
31+
const mSumSeq = memoize(sumSeq);
32+
33+
console.log('First call mSumSeq(2, 5)');
34+
console.log('Value: ' + mSumSeq(2, 5));
35+
console.log('Second call mSumSeq(2, 5)');
36+
console.log('From cache: ' + mSumSeq(2, 5));
37+
console.log('Call mSumSeq(2, 6)');
38+
console.log('Calculated: ' + mSumSeq(2, 6));

0 commit comments

Comments
 (0)