Skip to content

Instantly share code, notes, and snippets.

@jjhiggz
Created August 31, 2024 04:45
Show Gist options
  • Save jjhiggz/5ef754f45a67315035b880c5d4c7ed77 to your computer and use it in GitHub Desktop.
Save jjhiggz/5ef754f45a67315035b880c5d4c7ed77 to your computer and use it in GitHub Desktop.
moveToEnd generic
function moveAllInstancesToEnd<T extends any[] | string>(
input: T,
shouldMoveCb: (input: T[number]) => unknown
): T {
if(Array.isArray(input)){
let notMoved: any = []
let moved: any = []
for(let el of input){
if(shouldMoveCb(el)){
moved.push(el)
} else {
notMoved.push(el)
}
}
return [...notMoved, ...moved] as T
} else {
let notMoved = ""
let moved = ""
for(let el of input){
if(shouldMoveCb(el)){
moved += el
} else {
notMoved += el
}
}
return notMoved + moved as any
}
}
console.log(
moveAllInstancesToEnd("h0dsfj-000sdf0", n => n === "0")
)
console.log(
moveAllInstancesToEnd([1,0,1,0,1,0], n => n === 0)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment