Skip to content

Instantly share code, notes, and snippets.

@sebkolind
Last active April 26, 2022 05:19
Show Gist options
  • Save sebkolind/32b3692b9dd300368459ddbb7da1d0f1 to your computer and use it in GitHub Desktop.
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.
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