-
Notifications
You must be signed in to change notification settings - Fork 4
/
array-sort.js
59 lines (45 loc) · 1.3 KB
/
array-sort.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
var applyPatch = require("./apply-patch.js")
var setNonEnumerable = require("./lib/set-non-enumerable.js")
module.exports = sort
function sort(compare) {
var obs = this
var list = obs._list.slice()
var unpacked = unpack(list)
var sorted = unpacked
.map(function(it) { return it.val })
.sort(compare)
var packed = repack(sorted, unpacked)
//fake diff - for perf
//adiff on 10k items === ~3200ms
//fake on 10k items === ~110ms
var changes = [ [ 0, packed.length ].concat(packed) ]
var valueChanges = changes.map(applyPatch.bind(obs, sorted))
setNonEnumerable(sorted, "_diff", valueChanges)
obs._observSet(sorted)
return changes
}
function unpack(list) {
var unpacked = []
for(var i = 0; i < list.length; i++) {
unpacked.push({
val: ("function" == typeof list[i]) ? list[i]() : list[i],
obj: list[i]
})
}
return unpacked
}
function repack(sorted, unpacked) {
var packed = []
while(sorted.length) {
var s = sorted.shift()
var indx = indexOf(s, unpacked)
if(~indx) packed.push(unpacked.splice(indx, 1)[0].obj)
}
return packed
}
function indexOf(n, h) {
for(var i = 0; i < h.length; i++) {
if(n === h[i].val) return i
}
return -1
}