Jim - 19 days ago 6

Javascript Question

Given a rotate function like the one below, which rotates the array a set number of slots.

Is there an equivalent Ramda.js function or composition that will do this rotation?

`var test = [1,2,3,4,5,6,7,8,9];`

function rotate(arr, count) {

arr = arr.slice();

while (count < 0) {

count += arr.length;

}

count %= arr.length;

if (count) {

arr.splice.apply(arr, [0, 0].concat([].slice.call(arr.splice(arr.length - count, count))));

}

return arr;

}

`rotate(test, 2) // -> [8, 9, 1, 2, 3, 4, 5, 6, 7]`

Answer

This is similar to @donnut's answer, but includes modulo arithmetic to handle counts which exceed the length of the given list:

```
var rotate2 = function(xs, count) {
var n = -(count % xs.length);
return R.concat(R.slice(n, Infinity, xs),
R.slice(0, n, xs));
};
```

Here's a mutation-free equivalent which doesn't use Ramda at all:

```
var rotate3 = function(xs, count) {
var n = -(count % xs.length);
return xs.slice(n).concat(xs.slice(0, n));
};
```

Both solutions are significantly more declarative than the solution in the original post.

Source (Stackoverflow)

Comments