Can a "Rest" Operator Get Written in Javascript which Doesn't use Iteration?

1399 views javascript
1

In Lisps that I've seen there usually exists a 'rest' operator which returns all elements of a list in the same order, without the 0th element of that list. Without using iteration (no for or while loops), and without iteration happening via some other function or method does there exist a way to create a similar rest operator in Javascript?

For example, rest([1, 2, 3]) should return [2, 3], and rest([10, 2, 6]) should return [2, 6], and in general where 'arr' is the passed in array rest([arr[0], ..., arr[n]]) should return [arr[1], ..., arr[n]].

I had the idea of having a default value of 0 for a hidden 'counter' parameter of rest, but what I have below doesn't quite work:

function rest(arr, counter = 0) 
{
  if (counter === arr.length)
{
  return [];
}
  else
    {
      rest(arr, counter + 1)[0] = arr[counter]
    }
}

answered question

Are you looking for arr.slice(1)?

“without iteration happening via some other function or method” isn’t going to happen. JavaScript arrays aren’t linked lists.

2 Answers

11

In ES6, you can use rest syntax of Array destructuring. As from Docs:

When destructuring an array, you can unpack and assign the remaining part of it to a variable using the rest pattern:

Demo:

let rest = (arr) => {
  let [first, ...rest] = arr;
  return rest;
};

console.log(rest([1, 2, 3]));
console.log(rest([10, 5, 6]));

posted this
1

I would simply use Rename on Refactor. Simply right-click to name of class in code and navigate to Refactor --> Rename (or use Shift + Command + R shortcut).

enter image description here

Then if your class has the same name as is name of your file, it should rename it everywhere including the name of file

make sure that you're renaming it everywhere (if you see it with gray background simply click on it)

enter image description here

posted this

Have an answer?

JD

Please login first before posting an answer.