Created
August 31, 2024 04:45
-
-
Save jjhiggz/5ef754f45a67315035b880c5d4c7ed77 to your computer and use it in GitHub Desktop.
moveToEnd generic
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
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