Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to method chain .push and .shift array methods?

Here's my code:

var myArr = [1,2,3,4,5];
function queue(arr, item) {
  return arr.push(item).shift();
}

I'm attempting to create a function queue which takes an "array" and an "item" as arguments. I need to

  1. Add the item onto the end of the array
  2. Remove the first element of the array
  3. Return the element that was removed.

My code is not working. Can you help me figure this out?

like image 654
Matt Anderson Avatar asked May 07 '26 19:05

Matt Anderson


2 Answers

Just don't chain the method calls:

function queue(arr, item) {
  arr.push(item);
  return arr.shift();
}

Or, if you want a single statement,

function queue(arr, item) {
  return arr.push(item), arr.shift();
}

Alternatively, if you are mad enough, you could subclass Array and add a chainable push:

class MyArray extends Array {
  chainablePush(item) {
    this.push(item);
    return this;
  }
}
var myArr = new MyArray(1,2,3);
myArr.chainablePush(4).shift(); // 1
myArr; // MyArray [2,3,4];
like image 142
Oriol Avatar answered May 10 '26 08:05

Oriol


because arr.push returns the length of the array, you can't chain the shift like that

simply do this

function queue(arr, item) {
  arr.push(item);
  return arr.shift();
}
like image 28
Jaromanda X Avatar answered May 10 '26 09:05

Jaromanda X



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!