GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Memoization/JavaScript/5-sha.js at master · HowProgrammingWorks/Memoization Expand file tree/ Copy path5-sha.jsMore file actions 42 lines (32 loc) · 899 Bytes / Copy path5-sha.jsFile metadata and controls42 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)); |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |