-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmapped-array.js
58 lines (48 loc) · 1.35 KB
/
mapped-array.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
var MutantMap = require('./map')
var MutantArray = require('./array')
module.exports = MutantMappedArray
function MutantMappedArray (defaultItems, lambda, opts) {
opts = opts || {}
var list = MutantArray(defaultItems, {
comparer: opts.comparer,
fixedIndexing: true
})
var obs = MutantMap(list, lambda, opts)
obs.set = list.set
obs.push = function (item) {
list.push(item)
return obs.get(obs.getLength() - 1)
}
obs.insert = function (item, at) {
list.insert(item, at)
return obs.get(at)
}
obs.remove = function (mappedItem) {
var index = obs.indexOf(mappedItem)
if (~index) {
list.deleteAt(index)
return true
}
}
obs.move = function (mappedItem, targetIndex) {
var currentIndex = obs.indexOf(mappedItem)
if (~currentIndex && currentIndex !== targetIndex) {
var item = list.get(currentIndex)
if (currentIndex < targetIndex) {
list.transaction(function () {
list.insert(item, targetIndex + 1)
list.deleteAt(currentIndex)
})
} else if (currentIndex > targetIndex) {
list.transaction(function () {
list.insert(item, targetIndex)
list.deleteAt(currentIndex + 1)
})
}
if (typeof opts.onMove === 'function') {
opts.onMove(mappedItem, currentIndex, targetIndex)
}
}
}
return obs
}