Queue and Stack in javascript

Using basic array functions, you can treat an array as a queue (first in first out) or a stack (last in first out);

To act as a queue, use the shift function:

while (arr.length) {
  let val = arr.shift();
  console.log(val);
}

To act as a stack, use the pop function:

while (arr.length) {
  let val = arr.pop();
  console.log(val);
}

Array.map

Definition

[].map(function(currVal, idx, arr) { }[, thisArg]);

Sample Code

// Simple
var arr = ["a", "b", "c"];
var helloArr = arr.map(function(x) { return "Hello " + x; });
helloArr.forEach(console.log);

// Using thisArg
var item = { sum: 0 };
var newArray = [1,2,3].map(function(x) { this.sum += x; return x * 10; }, item);
console.log(item.sum); // 6
console.log(newArray); // [10,20,30]

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Polyfill

if (!Array.prototype.map) {
  Array.prototype.map = function(callback/*, thisArg*/) {
    var T, A, k;
    if (this == null) {
      throw new TypeError('this is null or not defined');
    }
    var O = Object(this);
    var len = O.length >>> 0;
    if (typeof callback !== 'function') {
      throw new TypeError(callback + ' is not a function');
    }
    if (arguments.length > 1) {
      T = arguments[1];
    }
    A = new Array(len);
    k = 0;
    while (k < len) {
      var kValue, mappedValue;
      if (k in O) {
        kValue = O[k];
        mappedValue = callback.call(T, kValue, k, O);
        A[k] = mappedValue;
      }
      k++;
    }
    return A;
  };
}

Array functions in javascript

[].splice

Removes elements from an array, returns the removed items as an array, and optionally replaces the items.

Definition

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Sample Code

var arr = [1, 2, 3, 4, 5];
var result = arr.splice(1, 2, "A", "B", "C");
console.log(arr); // [1, "A", "B", "C", 4, 5]
console.log(result); // [2, 3]

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

[].slice

Returns a sub-array, leaving the original array as-is. Use negative begin value as an offset from the last element.

Definition

arr.slice([begin[, end]])

Sample Code

var arr = [1, 2, 3, 4, 5];
var result = arr.slice(2, 4);
console.log(arr); // [1, 2, 3, 4, 5]
console.log(result); // [3, 4]

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

[].shift

Removes the first element of an array and returns it. The original array is modified. This can be used to treat an array as a queue (first in, first out).

Definition

arr.shift()

Sample Code

var arr = [1,2,3];
while (arr.length) {
  let val = arr.shift();
  console.log(val); // 1, then 2, then 3
}
console.log(arr); // []

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift

[].unshift

Inserts one or more items to the beginning of an array. It returns the new array count.

Definition

arr.unshift(element1[, ...[, elementN]])

Sample Code

var arr = [1,2,3,4];
var x = arr.unshift("a", "b"); // arr = ["a","b",1,2,3,4], x=6

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift

[].push

Adds one or more items to the end of an array. It returns the new array count.

Definition

arr.push(element1[, ...[, elementN]])

Sample Code

var arr = [1,2,3,4];
var x = arr.push("a", "b"); // arr = [1,2,3,4,"a","b"], x=6

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

[].pop

Removes the last element of an array and returns it. The original array is modified. This can be used to treat an array as a stack (last in, first out).

Definition

arr.pop()

Sample Code

var arr = [];
arr.push(1);
arr.push(2);
arr.push(3);
while (arr.length) {
    let x = arr.pop();
    console.log(x); // 3, then 2, then 1
}
console.log(arr); // []

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop

Browser Requirements

These all are basic array functions, and work on all browsers.

Array.from

Sometimes you’ll have an array-like object, and you want to convert it to an actual array. Some good ones are the arguments in a function, and strings, which get converted to an array of 1-character strings.

There’s an optional parameter for a mapping function, but in my opinion, if you want to do that, do it separate and chain it – it’ll keep things much clearer. Unless of course you’ve got a huge array, or are microoptimizing, and need to keep resources at a minimum.

Like some of the other array functions, the “thisArg” parameter just seems weird to me, but if you want to use it, go for it.

Definition

Array.from(arrayLikeObject [,mapFunction][,thisArg]);

Sample Code

// Old Way
function go() {
  var arr = Array.prototype.slice.call(arguments);
  arr.forEach(x => console.log(x));
}

// New Way
function go6() {
  var arr = Array.from(arguments);
  arr.forEach(x => console.log(x));
}

go(1, 2, 3); // 1, 2, 3
go6(4, 5, 6); // 4, 5, 6

Reference

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Browser Requirements

Requires Edge or a real browser – looks like no IE support at all

Polyfill

// Production steps of ECMA-262, Edition 6, 22.1.2.1

if (!Array.from) {
  Array.from = (function () {
    var toStr = Object.prototype.toString;
    var isCallable = function (fn) {
      return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
    };
    var toInteger = function (value) {
      var number = Number(value);
      if (isNaN(number)) { return 0; }
      if (number === 0 || !isFinite(number)) { return number; }
      return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
    };
    var maxSafeInteger = Math.pow(2, 53) - 1;
    var toLength = function (value) {
      var len = toInteger(value);
      return Math.min(Math.max(len, 0), maxSafeInteger);
    };

    // The length property of the from method is 1.
    return function from(arrayLike/*, mapFn, thisArg */) {
      // 1. Let C be the this value.
      var C = this;

      // 2. Let items be ToObject(arrayLike).
      var items = Object(arrayLike);

      // 3. ReturnIfAbrupt(items).
      if (arrayLike == null) {
        throw new TypeError('Array.from requires an array-like object - not null or undefined');
      }

      // 4. If mapfn is undefined, then let mapping be false.
      var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
      var T;
      if (typeof mapFn !== 'undefined') {
        // 5. else
        // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
        if (!isCallable(mapFn)) {
          throw new TypeError('Array.from: when provided, the second argument must be a function');
        }

        // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (arguments.length > 2) {
          T = arguments[2];
        }
      }

      // 10. Let lenValue be Get(items, "length").
      // 11. Let len be ToLength(lenValue).
      var len = toLength(items.length);

      // 13. If IsConstructor(C) is true, then
      // 13. a. Let A be the result of calling the [[Construct]] internal method 
      // of C with an argument list containing the single item len.
      // 14. a. Else, Let A be ArrayCreate(len).
      var A = isCallable(C) ? Object(new C(len)) : new Array(len);

      // 16. Let k be 0.
      var k = 0;
      // 17. Repeat, while k < len… (also steps a - h)
      var kValue;
      while (k < len) {
        kValue = items[k];
        if (mapFn) {
          A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
        } else {
          A[k] = kValue;
        }
        k += 1;
      }
      // 18. Let putStatus be Put(A, "length", len, true).
      A.length = len;
      // 20. Return A.
      return A;
    };
  }());
}

Array.forEach

Definition

arr.forEach(function callback(currentValue, index, array) {
  //your iterator
}[, thisArg]);

Sample Code

var arr = ["a", "b", "c"];

arr.forEach(function(x) { console.log(x); });

Using thisArg

I actually can’t think of a good purpose for this – any example I see can be done differently, and it would be clearer in my opinion. But I’m sure there are some good use cases:

var item = { sum: 0 };

[1,2,3].forEach(function(x) { this.sum += x; }, item);

console.log(item.sum); // 6

Notes

Weird things happen when you add or remove items from the array. I would recommend never modifying the array from within forEach.

Reference

Mozilla – array.forEach

Browser Requirements

Requires IE9+ or a real browser

Polyfill

if (!Array.prototype.forEach) {
 Array.prototype.forEach = function(callback) {
  var T, k;
  if (this == null) {
    throw new TypeError('this is null or not defined');
  }

  var O = Object(this);
  var len = O.length >>> 0;
  if (typeof callback !== 'function') {
    throw new TypeError(callback + ' is not a function');
  }
  if (arguments.length > 1) {
    T = arguments[1];
  }
  k = 0;
  while (k < len) {
    var kValue;
    if (k in O) {
      kValue = O[k];
      callback.call(T, kValue, k, O);
    }
    k++;
  }
 };
}