Last active
April 26, 2022 05:19
-
-
Save sebkolind/32b3692b9dd300368459ddbb7da1d0f1 to your computer and use it in GitHub Desktop.
Move all items in an array in either direction by one in Typescript. Does not mutate the source array, and returns a new array.
This file contains hidden or 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 arrayMoveByOne(source: unknown[], reverse = false): unknown[] { | |
const s = [...source]; | |
const c = [...s]; | |
let i = 0; | |
while (i < s.length) { | |
if (reverse) { | |
if (s[i - 1] == null) { | |
c[s.length - 1] = s[0]; | |
} else { | |
c[i - 1] = s[i]; | |
} | |
} else { | |
if (s[i + 1] == null) { | |
c[0] = s[s.length - 1]; | |
} else { | |
c[i + 1] = s[i]; | |
} | |
} | |
i++; | |
} | |
return c; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment