1 | var MutantMap = require('./map')
|
2 | var MutantArray = require('./array')
|
3 |
|
4 | module.exports = MutantMappedArray
|
5 |
|
6 | function MutantMappedArray (defaultItems, lambda, opts) {
|
7 | opts = opts || {}
|
8 |
|
9 | var list = MutantArray(defaultItems, {
|
10 | comparer: opts.comparer,
|
11 | fixedIndexing: true
|
12 | })
|
13 |
|
14 | var obs = MutantMap(list, lambda, opts)
|
15 | obs.set = list.set
|
16 |
|
17 | obs.push = function (item) {
|
18 | list.push(item)
|
19 | return obs.get(obs.getLength() - 1)
|
20 | }
|
21 |
|
22 | obs.insert = function (item, at) {
|
23 | list.insert(item, at)
|
24 | return obs.get(at)
|
25 | }
|
26 |
|
27 | obs.remove = function (mappedItem) {
|
28 | var index = obs.indexOf(mappedItem)
|
29 | if (~index) {
|
30 | list.deleteAt(index)
|
31 | return true
|
32 | }
|
33 | }
|
34 |
|
35 | obs.move = function (mappedItem, targetIndex) {
|
36 | var currentIndex = obs.indexOf(mappedItem)
|
37 | if (~currentIndex && currentIndex !== targetIndex) {
|
38 | var item = list.get(currentIndex)
|
39 | if (currentIndex < targetIndex) {
|
40 | list.transaction(function () {
|
41 | list.insert(item, targetIndex + 1)
|
42 | list.deleteAt(currentIndex)
|
43 | })
|
44 | } else if (currentIndex > targetIndex) {
|
45 | list.transaction(function () {
|
46 | list.insert(item, targetIndex)
|
47 | list.deleteAt(currentIndex + 1)
|
48 | })
|
49 | }
|
50 |
|
51 | if (typeof opts.onMove === 'function') {
|
52 | opts.onMove(mappedItem, currentIndex, targetIndex)
|
53 | }
|
54 | }
|
55 | }
|
56 |
|
57 | return obs
|
58 | }
|