-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetho-function.js
50 lines (43 loc) · 1000 Bytes
/
metho-function.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
import * as Metho from "metho"
const
curryKey = Symbol('Curried function'),
memoKey = Symbol('Memoised function')
const target = Function.prototype
// Curried
export const curried = Metho.add(
target,
function curried() {
return this[curryKey] || (this[curryKey]=curry(this))
}
)
// Memoised
export const memoised = Metho.add(
target,
function memoised() {
return this[memoKey] || (this[memoKey]=memo(this))
}
)
export const memoized = memoised
// generic currying function
function curry(func) {
return function curried(...args) {
if (args.length >= func.length) {
return func.apply(this, args)
} else {
return function(...args2) {
return curried.apply(this, args.concat(args2))
}
}
}
}
// generic memoisation function
function memo(func) {
const cache = new Map()
return function memoised(...args) {
const key = JSON.stringify(args)
if (cache.has(key)) return cache.get(key)
const result = func(...args)
cache.set(key, result)
return result
}
}