dhis2/d2-utilizr

View on GitHub
src/arrayReplace.js

Summary

Maintainability
A
25 mins
Test Coverage
/**
 * Replace values in an array with given values or remove values from an array.
 *
 * @param {Array} array The array where the values should be replaced
 * @param {number} index The index in the array where to start the replacement
 * @param {number} removeCount The number of items to remove
 * @param {*} insert The item(s) to be inserted
 * @returns {Array} The array with the replaced values
 *
 * @example
 * const sourceArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
 * arrayReplace(sourceArray, 0, 5, ['a', 'b', 'c', 'd']); // Returns: ['a', 'b', 'c', 'd', 6, 7, 8, 9, 10]
 */
export default function arrayReplace(array, index, removeCount, insert) {
    if (insert && insert.length) {
        if (index < array.length) {
            array.splice.apply(array, [index, removeCount].concat(insert));
        } else {
            array.push.apply(array, insert);
        }
    } else {
        array.splice(index, removeCount);
    }
    return array;
}