UNPKG

@wezom/toolkit-array

Version:
34 lines (30 loc) 808 B
'use strict'; var clone = require('./clone.js'); /** * Adds an element to an array or removes if the array already has such an element * @immutable * @example * arrayToggleItem([1, 2, 3], 9); // => [1, 2, 3, 9] * arrayToggleItem([1, 2, 3, 9], 2); // => [1, 3, 9] * arrayToggleItem( * [{ x: 1 }, { x: 2 }, { x: 3 }], * { x: 2 }, * (array, item) => array.findIndex((el) => el.x === item.x), * ); // => [{ x: 1 }, { x: 3 }] */ function toggleItem(array, item, predicate) { if (predicate === void 0) { predicate = function (array, item) { return array.indexOf(item); }; } var clone$1 = clone(array); var index = predicate(clone$1, item); if (index >= 0) { clone$1.splice(index, 1); } else { clone$1.push(item); } return clone$1; } module.exports = toggleItem;