[英]How can I rotate an array to the left if the number of rotation is negative and to the right if number of rotation is positive using JAVASCRIPT
编写一个名为dynamicRotate(num)
的 function 。 调用时, dynamicRotate
function 将接受一个数字作为旋转量并返回 function。 正数向右旋转数组,负数向左旋转。 dynamicRotate 返回的dynamicRotate
将接受一个数组,该数组将按第一次调用dynamicRotate
时提供的量旋转。 它将返回由给定旋转改变的原始数组。
例子:
let arr = ['a', 'b', 'c', 'd', 'e'];
rotateRight = dynamicRotate(2);
rotateRight(arr);
console.log(arr) // prints - [ 'd', 'e', 'a', 'b', 'c' ]
animals = ['wombat', 'koala', 'opossum', 'kangaroo'];
rotateLeft = dynamicRotate(-1);
rotateLeft(animals);
console.log(animals) // prints - [ 'koala', 'opossum', 'kangaroo', 'wombat' ]
这是我到目前为止所做的工作
function dynamicRotate(num) {
return (arr) => {
if (arr.length === 0) {
return [];
}
let rotatedArr = arr.concat();
if (num < 0) {
num = Math.abs(num);
}
for (let i = 0; i <= num; i++) {
let frontItem = rotatedArr.shift(); // [a, b , c] so now rotatedArr = [d, e]
rotatedArr.push(frontItem);
}
return rotatedArr;
}
}
诀窍是只做必要的旋转。 例如,如果arr
的长度为 5,并且您想要进行 7 次旋转,那么您只需执行 2 次旋转,因为每 5 次旋转意味着您回到了原始的arr
state。
从那里您可以从左侧或右侧splice
阵列并将生成的部分重新组合在一起。 同样重要的是,您使用rotateRight(...);
的返回值重新分配arr
或animals
数组; 或rotateLeft(...);
function。
我希望您会尝试了解发生了什么,而不仅仅是复制和粘贴。
function dynamicRotate(num) { return (arr) => { // Modulo rotate num to get max needed rotations (arr.length = num => elements don't change position) const operationsLeftover = num % arr.length; let returnArray; if (operationsLeftover == 0) { // No change return arr; }else if (operationsLeftover > 0){ // To the right returnArray = arr.slice(arr.length - operationsLeftover); returnArray = returnArray.concat(arr.slice(0, arr.length - operationsLeftover)); }else { // To the left returnArray = arr.slice(0, Math.abs(operationsLeftover)); returnArray = arr.slice(Math.abs(operationsLeftover)).concat(returnArray); } return returnArray; } } let arr = ['a', 'b', 'c', 'd', 'e']; rotateRight = dynamicRotate(2); arr = rotateRight(arr); console.log(arr) // prints - [ 'd', 'e', 'a', 'b', 'c' ] animals = ['wombat', 'koala', 'opossum', 'kangaroo']; rotateLeft = dynamicRotate(-1); animals = rotateLeft(animals); console.log(animals) // prints - [ 'koala', 'opossum', 'kangaroo', 'wombat' ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.