UNPKG

immutable-class

Version:

A template for creating immutable classes

74 lines (73 loc) 2.28 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.SimpleArray = void 0; class SimpleArray { static mapImmutable(array, fn) { let changed = false; const newArray = array.map((x, i) => { const newX = fn(x, i); if (newX !== x) changed = true; return newX; }); return changed ? newArray : array; } static append(array, value) { return array.concat([value]); } static change(array, index, value) { array = array.slice(); array[index] = value; return array; } static find(array, fn) { for (let i = 0, n = array.length; i < n; i++) { const a = array[i]; if (fn.call(array, a, i)) return a; } return; } static findIndex(array, fn) { for (let i = 0, n = array.length; i < n; i++) { const a = array[i]; if (fn.call(array, a, i)) return i; } return -1; } static delete(array, arg) { return array.filter((a, i) => typeof arg === 'function' ? !arg(a, i) : a !== arg); } static deleteIndex(array, index) { return array.filter((_a, i) => i !== index); } static contains(array, arg) { if (typeof arg !== 'function') return array.includes(arg); return SimpleArray.findIndex(array, arg) !== -1; } static insertIndex(array, index, value) { array = array.slice(); array.splice(index, 0, value); return array; } static moveIndex(array, itemIndex, insertIndex) { const n = array.length; if (itemIndex < 0 || itemIndex >= n) throw new Error('itemIndex out of range'); if (insertIndex < 0 || insertIndex > n) throw new Error('insertIndex out of range'); const newArray = []; array.forEach((value, i) => { if (i === insertIndex) newArray.push(array[itemIndex]); if (i !== itemIndex) newArray.push(value); }); if (n === insertIndex) newArray.push(array[itemIndex]); return newArray; } } exports.SimpleArray = SimpleArray;