UNPKG

1.91 kBJavaScriptView Raw
1var __spreadArrays = (this && this.__spreadArrays) || function () {
2 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
3 for (var r = Array(s), k = 0, i = 0; i < il; i++)
4 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
5 r[k] = a[j];
6 return r;
7};
8/**
9 * Moves an item from one position to another, checking that the indexes given are within bounds.
10 *
11 * @example
12 * const source = observable([1, 2, 3])
13 * moveItem(source, 0, 1)
14 * console.log(source.map(x => x)) // [2, 1, 3]
15 *
16 * @export
17 * @param {ObservableArray<T>} target
18 * @param {number} fromIndex
19 * @param {number} toIndex
20 * @returns {ObservableArray<T>}
21 */
22export function moveItem(target, fromIndex, toIndex) {
23 checkIndex(target, fromIndex);
24 checkIndex(target, toIndex);
25 if (fromIndex === toIndex) {
26 return;
27 }
28 var oldItems = target.slice();
29 var newItems;
30 if (fromIndex < toIndex) {
31 newItems = __spreadArrays(oldItems.slice(0, fromIndex), oldItems.slice(fromIndex + 1, toIndex + 1), [
32 oldItems[fromIndex]
33 ], oldItems.slice(toIndex + 1));
34 }
35 else {
36 // toIndex < fromIndex
37 newItems = __spreadArrays(oldItems.slice(0, toIndex), [
38 oldItems[fromIndex]
39 ], oldItems.slice(toIndex, fromIndex), oldItems.slice(fromIndex + 1));
40 }
41 target.replace(newItems);
42 return target;
43}
44/**
45 * Checks whether the specified index is within bounds. Throws if not.
46 *
47 * @private
48 * @param {ObservableArray<any>} target
49 * @param {number }index
50 */
51function checkIndex(target, index) {
52 if (index < 0) {
53 throw new Error("[mobx.array] Index out of bounds: " + index + " is negative");
54 }
55 var length = target.length;
56 if (index >= length) {
57 throw new Error("[mobx.array] Index out of bounds: " + index + " is not smaller than " + length);
58 }
59}