index.js
2.56 KB
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
//
// Main
//
function memoize (fn, options) {
var cache = options && options.cache
? options.cache
: cacheDefault
var serializer = options && options.serializer
? options.serializer
: serializerDefault
var strategy = options && options.strategy
? options.strategy
: strategyDefault
return strategy(fn, {
cache: cache,
serializer: serializer
})
}
//
// Strategy
//
function isPrimitive (value) {
return value == null || typeof value === 'number' || typeof value === 'boolean' // || typeof value === "string" 'unsafe' primitive for our needs
}
function monadic (fn, cache, serializer, arg) {
var cacheKey = isPrimitive(arg) ? arg : serializer(arg)
var computedValue = cache.get(cacheKey)
if (typeof computedValue === 'undefined') {
computedValue = fn.call(this, arg)
cache.set(cacheKey, computedValue)
}
return computedValue
}
function variadic (fn, cache, serializer) {
var args = Array.prototype.slice.call(arguments, 3)
var cacheKey = serializer(args)
var computedValue = cache.get(cacheKey)
if (typeof computedValue === 'undefined') {
computedValue = fn.apply(this, args)
cache.set(cacheKey, computedValue)
}
return computedValue
}
function assemble (fn, context, strategy, cache, serialize) {
return strategy.bind(
context,
fn,
cache,
serialize
)
}
function strategyDefault (fn, options) {
var strategy = fn.length === 1 ? monadic : variadic
return assemble(
fn,
this,
strategy,
options.cache.create(),
options.serializer
)
}
function strategyVariadic (fn, options) {
var strategy = variadic
return assemble(
fn,
this,
strategy,
options.cache.create(),
options.serializer
)
}
function strategyMonadic (fn, options) {
var strategy = monadic
return assemble(
fn,
this,
strategy,
options.cache.create(),
options.serializer
)
}
//
// Serializer
//
function serializerDefault () {
return JSON.stringify(arguments)
}
//
// Cache
//
function ObjectWithoutPrototypeCache () {
this.cache = Object.create(null)
}
ObjectWithoutPrototypeCache.prototype.has = function (key) {
return (key in this.cache)
}
ObjectWithoutPrototypeCache.prototype.get = function (key) {
return this.cache[key]
}
ObjectWithoutPrototypeCache.prototype.set = function (key, value) {
this.cache[key] = value
}
var cacheDefault = {
create: function create () {
return new ObjectWithoutPrototypeCache()
}
}
//
// API
//
module.exports = memoize
module.exports.strategies = {
variadic: strategyVariadic,
monadic: strategyMonadic
}