Skip to content

Instantly share code, notes, and snippets.

@aeinbu
Last active October 28, 2023 22:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aeinbu/40f1a84c8bfa1802f54fecc6fb0570c2 to your computer and use it in GitHub Desktop.
Save aeinbu/40f1a84c8bfa1802f54fecc6fb0570c2 to your computer and use it in GitHub Desktop.
Array operations for useReducer or Redux with ES6+
// Returns a new array, with the element at pos replaced with replacement item or calling the replacement function on arr[pos]
function changeAtIndex(arr, pos, replacement) {
if (typeof replacement == "function") {
replacement = replacement(arr[pos]);
}
return [...arr.slice(0, pos), replacement, ...arr.slice(pos + 1)];
}
// Returns a new array, with the first element matching the predicate function replaced with replacement item or calling the replacement function on arr[pos]
function changeAtKey(arr, predicate, replacement) {
return changeAtIndex(arr, predicate(arr), replacement);
}
// Returns a new array, with the insertion element inserted at pos
function insertAtIndex(arr, pos, insertion) {
return [...arr.slice(0, pos), insertion, ...arr.slice(pos)];
}
// Returns a new array, with the element at pos removed
function removeAtIndex(arr, pos) {
return [...arr.slice(0, pos), ...arr.slice(pos + 1)];
}
// Returns a new array with the element matching the predicate removed
function removeAtKey(arr, predicate){
return removeAtIndex(arr, predicate(arr));
}
type ReplaceFn<TData> = (data: TData) => TData
// Returns a new array, with the element at pos replaced with replacement item or calling the replacement function on arr[pos]
export function changeAtIndex<TData>(inArray: Array<TData>, index: number, replacement: TData | ReplaceFn<TData>) {
if (typeof replacement == "function") {
replacement = (replacement as ReplaceFn<TData>)(inArray[index])
}
return [...inArray.slice(0, index), replacement, ...inArray.slice(index + 1)]
}
// Returns a new array, with the insertion element inserted at pos
export function insertAtIndex<TData>(inArray: Array<TData>, index: number, insertion: TData) {
return [...inArray.slice(0, index), insertion, ...inArray.slice(index)];
}
// Returns a new array, with the element at pos removed
export function removeAtIndex<TData>(inArray: Array<TData>, index: number) {
return [...inArray.slice(0, index), ...inArray.slice(index + 1)];
}
// Returns a new array, with with an element moved from fromIndex to toIndex
export function moveInArray<TData>(inArray: Array<TData>, fromIndex: number, toIndex: number) {
const outArray = [...inArray]
const [itemToMove] = outArray.splice(fromIndex, 1)
outArray.splice(toIndex, 0, itemToMove)
return outArray
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment