-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
93 lines (83 loc) · 2.04 KB
/
index.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
var has = Object.prototype.hasOwnProperty
var toString = Object.prototype.toString
var enumerable = Object.prototype.propertyIsEnumerable
var hasSymbol = typeof Symbol === 'function'
reduce.reduced = Reduced
reduce.isReduced = isReduced
reduce.unwrap = unwrap
reduce._reduce = _reduce
module.exports = reduce
function reduce (stuff, fn, acc) {
return unwrap(_reduce(stuff, fn, acc))
}
function _reduce (stuff, fn, acc) {
if (!stuff) return acc
if (toString.call(stuff) === '[object Map]') {
return reduceMap(stuff, fn, acc)
}
if (hasSymbol && Symbol.iterator && stuff[Symbol.iterator]) {
return reduceIt(stuff[Symbol.iterator](), fn, acc)
}
return reduceObj(stuff, fn, acc)
}
function reduceObj (obj, fn, acc) {
var next = acc
for (var i in obj) {
if (has.call(obj, i)) {
next = fn(next, obj[i], i)
if (isReduced(next)) return next
}
}
if (typeof Object.getOwnPropertySymbols === 'function') {
var symbols = Object.getOwnPropertySymbols(obj)
var key
for (var j = 0; j < symbols.length; j++) {
key = symbols[j]
if (enumerable.call(obj, key)) {
next = fn(next, obj[key], key)
if (isReduced(next)) return next
}
}
}
return next
}
function reduceIt (it, fn, acc) {
var inserted = 0
var step = null
var next = acc
while (true) {
step = it.next()
if (step.done) break;
next = fn(next, step.value, '' + inserted++)
if (isReduced(next)) return next
}
return next
}
function reduceMap (map, fn, acc) {
var step = null
var next = acc
var it = map.entries()
while (true) {
step = it.next()
if (step.done) break;
next = fn(next, step.value[1], step.value[0])
if (isReduced(next)) return next
}
return next
}
function Reduced (val) {
return {
'@@transducer/reduced': true,
'@@transducer/value': val
}
}
function unwrap (val) {
while (isReduced(val)) {
val = val['@@transducer/value']
}
return val
}
function isReduced (val) {
if (val == null) return false
return val['@@transducer/reduced'] === true
}