-
Notifications
You must be signed in to change notification settings - Fork 4
/
splice.js
50 lines (40 loc) · 1.51 KB
/
splice.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
var slice = Array.prototype.slice
var addListener = require("./add-listener.js")
var setNonEnumerable = require("./lib/set-non-enumerable.js");
module.exports = splice
// `obs.splice` is a mutable implementation of `splice()`
// that mutates both `list` and the internal `valueList` that
// is the current value of `obs` itself
function splice(index, amount) {
var obs = this
var args = slice.call(arguments, 0)
var valueList = obs().slice()
// generate a list of args to mutate the internal
// list of only obs
var valueArgs = args.map(function (value, index) {
if (index === 0 || index === 1) {
return value
}
// must unpack observables that we are adding
return typeof value === "function" ? value() : value
})
valueList.splice.apply(valueList, valueArgs)
// we remove the observs that we remove
var removed = obs._list.splice.apply(obs._list, args)
var extraRemoveListeners = args.slice(2).map(function (observ) {
return typeof observ === "function" ?
addListener(obs, observ) :
null
})
extraRemoveListeners.unshift(args[0], args[1])
var removedListeners = obs._removeListeners.splice
.apply(obs._removeListeners, extraRemoveListeners)
removedListeners.forEach(function (removeObservListener) {
if (removeObservListener) {
removeObservListener()
}
})
setNonEnumerable(valueList, "_diff", [valueArgs])
obs._observSet(valueList)
return removed
}