deno.land / x / rambda@v9.1.1 / source / memoize.js

نووسراو ببینە
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { compose } from './compose.js'import { map } from './map.js'import { replace } from './replace.js'import { sort } from './sort.js'import { take } from './take.js'import { type } from './type.js'
const cache = {}
const normalizeObject = obj => { const sortFn = (a, b) => a > b ? 1 : -1 const willReturn = {} compose(map(prop => willReturn[ prop ] = obj[ prop ]), sort(sortFn))(Object.keys(obj))
return willReturn}
const stringify = a => { const aType = type(a) if (aType === 'String'){ return a } else if ([ 'Function', 'Promise' ].includes(aType)){ const compacted = replace( /\s{1,}/g, ' ', a.toString() )
return replace( /\s/g, '_', take(15, compacted) ) } else if (aType === 'Object'){ return JSON.stringify(normalizeObject(a)) }
return JSON.stringify(a)}
const generateProp = (fn, ...inputArguments) => { let propString = '' inputArguments.forEach(inputArgument => { propString += `${ stringify(inputArgument) }_` })
return `${ propString }${ stringify(fn) }`}// with weakmapsexport function memoize(fn, ...inputArguments){ if (arguments.length === 1){ return (...inputArgumentsHolder) => memoize(fn, ...inputArgumentsHolder) }
const prop = generateProp(fn, ...inputArguments) if (prop in cache) return cache[ prop ]
if (type(fn) === 'Async'){ return new Promise(resolve => { fn(...inputArguments).then(result => { cache[ prop ] = result resolve(result) }) }) }
const result = fn(...inputArguments) cache[ prop ] = result
return result}
rambda

Version Info

Tagged at
2 months ago