Search code examples
javascriptarrayschaining

Chaining Methods error in Javascript


I would like to know the reason why this simple piece of code fails:

var arr = [1, 2, 3];
arr.push(arr[0]).shift();
console.log(arr);

it returns in firebug console "TypeError: arr.push(...).shift is not a function"

I think it happens because I invoke the shift() method not on an array but on the pushed element.

Is there a more elegant way to obtain the same result that,

var arr = [1, 2, 3];
arr.push(arr[0]);
arr.shift();
console.log(arr);

produce ?

Thanks in advance!


Solution

  • Essentially this question is saying, can I somehow "elegantly" express the notion of moving the first item of an array to the end. Luckily, JS is a Turing-complete language, which allows us to define functions, so the "elegant" answer is just

    rotate(arr)
    

    Now it merely remains to define rotate. To rotate is to drop the first element in the result of adding the head element to the end:

    function rotate(arr) { return drop(add(arr, head(arr))); }
    

    Now drop is

    function drop(arr) { return arr.shift(), arr; }
    

    and head of course is

    function head(arr) { return arr[0]; }
    

    and add is

    function add(arr, elt) { return arr.push(elt), arr; }
    

    Another approach

    I could also write a function to move n elements from position i to position j, using splice, as follows:

    function move(arr, n, i, j) {
        arr.splice.apply(arr, [j-n+1, 0].concat(arr.splice(i, n)));
        return arr;
    }
    

    Then to rotate is to move one element at the beginning to the end:

    function rotate(arr) { return move(arr, 1, 0, 999); }