diginext-utils
Version:
README.md
49 lines • 1.62 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.moveElement = moveElement;
/**
* Moves an element from one index to another in an array.
* Returns a new array without modifying the original.
*
* @template T - The type of elements in the array
* @param array - The array to modify
* @param fromIndex - The index of the element to move
* @param toIndex - The index to move the element to
* @returns A new array with the element moved
*
* @example
* ```ts
* moveElement([1, 2, 3, 4], 0, 2); // [2, 3, 1, 4]
* moveElement(['a', 'b', 'c'], 2, 0); // ['c', 'a', 'b']
* ```
*/
function moveElement(array, fromIndex, toIndex) {
if (!Array.isArray(array) || array.length === 0) {
return [];
}
// Normalize negative indices
const normalizedFrom = fromIndex < 0 ? array.length + fromIndex : fromIndex;
const normalizedTo = toIndex < 0 ? array.length + toIndex : toIndex;
// Validate indices
if (normalizedFrom < 0 || normalizedFrom >= array.length) {
return [...array];
}
const result = [...array];
const [element] = result.splice(normalizedFrom, 1);
// Element could be undefined if array access fails
if (element === undefined) {
return result;
}
// If toIndex is beyond array length, pad with undefined
if (normalizedTo >= result.length) {
while (result.length < normalizedTo) {
result.push(undefined);
}
result.push(element);
}
else {
result.splice(normalizedTo, 0, element);
}
return result;
}
//# sourceMappingURL=moveElement.js.map