UNPKG

mattermost-redux

Version:

Common code (API client, Redux stores, logic, utility functions) for building a Mattermost client

46 lines (45 loc) 1.9 kB
"use strict"; // Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. Object.defineProperty(exports, "__esModule", { value: true }); exports.insertWithoutDuplicates = insertWithoutDuplicates; exports.insertMultipleWithoutDuplicates = insertMultipleWithoutDuplicates; exports.removeItem = removeItem; // insertWithoutDuplicates inserts an item into an array and returns the result. The provided array is not modified. // If the array already contains the given item, that item is moved to the new location instead of adding a duplicate. // If the array already had the given item at the given index, the origianl array is returned. function insertWithoutDuplicates(array, item, newIndex) { const index = array.indexOf(item); if (newIndex === index) { // The item doesn't need to be moved since its location hasn't changed return array; } const newArray = [...array]; // Remove the item from its old location if it already exists in the array if (index !== -1) { newArray.splice(index, 1); } // And re-add it in its new location newArray.splice(newIndex, 0, item); return newArray; } function insertMultipleWithoutDuplicates(array, items, newIndex) { let newArray = [...array]; items.forEach((item) => { newArray = removeItem(newArray, item); }); // And re-add it in its new location newArray.splice(newIndex, 0, ...items); return newArray; } // removeItem removes an item from an array and returns the result. The provided array is not modified. If the array // did not originally contain the given item, the original array is returned. function removeItem(array, item) { const index = array.indexOf(item); if (index === -1) { return array; } const result = [...array]; result.splice(index, 1); return result; }