|
72 | 72 | const arr = [1, 2, 3, 4, 5]; |
73 | 73 | console.log("Rotated Array:", leftRotateByOne(arr)); |
74 | 74 | } |
| 75 | + |
| 76 | +// Approach 5: Using destructuring assignment and the spread operator |
| 77 | + |
| 78 | +{ |
| 79 | + function leftRotateByOne(arr) { |
| 80 | + if (arr.length <= 1) { |
| 81 | + return arr; |
| 82 | + } |
| 83 | + |
| 84 | + const [first, ...rest] = arr; |
| 85 | + const [firsts, ...third] = arr; |
| 86 | + console.log([firsts, ...third]); |
| 87 | + return [...rest, first]; |
| 88 | + } |
| 89 | + |
| 90 | + const arr = [1, 2, 3, 4, 5]; |
| 91 | + console.log("Rotated Array", leftRotateByOne(arr)); |
| 92 | +} |
| 93 | + |
| 94 | +// Approach 6: Using the reduce() Method |
| 95 | + |
| 96 | +{ |
| 97 | + function leftRotateByOneUsingReduce(arr) { |
| 98 | + if (arr.length <= 1) { |
| 99 | + return arr; |
| 100 | + } |
| 101 | + console.log([...arr.slice(1)]); |
| 102 | + return [...arr.slice(1).reduce((acc, curr) => [...acc, curr], []), arr[0]]; |
| 103 | + } |
| 104 | + const arr = [6, 7, 8, 9, 10]; |
| 105 | + const result = leftRotateByOneUsingReduce(arr); |
| 106 | + console.log("original array = ", arr); |
| 107 | + console.log("array after left rotation =", result); |
| 108 | +} |
| 109 | + |
| 110 | +// Approach 7: Using Array destructuring and Array.prototype.concat() |
| 111 | + |
| 112 | +{ |
| 113 | + function leftRotateByOne(arr) { |
| 114 | + if (arr.length <= 1) { |
| 115 | + return arr; |
| 116 | + } |
| 117 | + |
| 118 | + const [first, ...rest] = arr; |
| 119 | + return rest.concat(first); |
| 120 | + } |
| 121 | + |
| 122 | + const array = [10, 20, 30, 40, 50]; |
| 123 | + console.log("original array:", array); |
| 124 | + const rotatedArray = leftRotateByOne(arr); |
| 125 | + console.log("Array after left rotate by one:", rotatedArray); |
| 126 | +} |
0 commit comments