Last active
June 4, 2019 01:39
-
-
Save islishude/b3d422fbe0eaa502f7b3159b447944d8 to your computer and use it in GitHub Desktop.
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
/** | |
* move k index from array | |
* @param {number[]} arr | |
* @param {number} k | |
*/ | |
function move(arr, k) { | |
if (k == 0) { | |
return arr; | |
} | |
let length = arr.length; | |
k = Math.abs(k) % length; | |
if (k === length) { | |
return arr; | |
} | |
if (k > 0) { | |
return arr.slice(length - k).concat(arr.slice(0, length - k)); | |
} | |
if (k < 0) { | |
return arr.slice(k, length).concat(arr.slice(0, k)); | |
} | |
} | |
const arr = [1, 2, 3, 4, 5]; | |
console.log(0, move(arr, 0)); | |
console.log(1, move(arr, 1)); | |
console.log(2, move(arr, 2)); | |
console.log(6, move(arr, 6)); | |
console.log(-1, move(arr, -1)); | |
console.log(-2, move(arr, -2)); | |
console.log(-6, move(arr, -6)); | |
// 0 [ 1, 2, 3, 4, 5 ] | |
// 1 [ 5, 1, 2, 3, 4 ] | |
// 2 [ 4, 5, 1, 2, 3 ] | |
// 6 [ 5, 1, 2, 3, 4 ] | |
// -1 [ 5, 1, 2, 3, 4 ] | |
// -2 [ 4, 5, 1, 2, 3 ] | |
// -6 [ 5, 1, 2, 3, 4 ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment