Skip to content

Instantly share code, notes, and snippets.

@laphilosophia
Created December 30, 2022 12:33
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 laphilosophia/263dc4e20a08dbf19d630cfa101cb20e to your computer and use it in GitHub Desktop.
Save laphilosophia/263dc4e20a08dbf19d630cfa101cb20e to your computer and use it in GitHub Desktop.
Simple, shallow checked, remove item from array
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