Created
December 30, 2022 12:33
-
-
Save laphilosophia/263dc4e20a08dbf19d630cfa101cb20e to your computer and use it in GitHub Desktop.
Simple, shallow checked, remove item from array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function removeItem<T>(array: Array<T>) { | |
let cache = array | |
let count = array.length | |
let checkArrayContains = (() => Object.is(cache[0], cache[count - 1]))() | |
let findCurrentIndex = (key: any) => cache.findIndex((item: any) => item === key) | |
let immutableSlice = (start: number) => [...cache.slice(0, start), ...cache.slice(start + 1)] | |
if (!Array.isArray(cache)) throw new Error('type error! [array] expected!') | |
if (count === 0) throw new Error('provided array must contain at least one element') | |
if (checkArrayContains) { | |
throw new Error('provided array contains the same elements or contains less than two elements') | |
} | |
return (key: any) => { | |
let current = findCurrentIndex(key) | |
let result = immutableSlice(current) | |
cache = result | |
return cache | |
} | |
} | |
const array = [1, 'ipsum', 3, 0x00f5f5, Symbol] | |
const remove = removeItem(array) | |
console.log(remove(Symbol)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment