Sha256: 324e8ad9079206241b633dc1160bcc57e683d3c28f0c50ba8f42e186ee5870e5

Contents?: true

Size: 1.41 KB

Versions: 47

Compression:

Stored size: 1.41 KB

Contents

'use strict';

function List(arr) {
  this.values = arr || [];
}

List.prototype = {
  append: function (otherList) {
    var appended = this.values;

    for (var i = 0; i < otherList.length(); i++) {
      appended.push(otherList.values[i]);
    }

    return new List(appended);
  },

  concat: function (otherList) {
    return this.append(otherList);
  },

  cons: function (item, arr) {
    var x = new List([item]);
    var xs = new List(arr)
    return x.append(xs).values;
  },

  foldl: function (func, start) {
    var acc = start;

    for (var i = 0; i < this.length(); i++) {
      acc = func(this.values[i], acc);
    }

    return acc;
  },

  foldr: function (func, start) {
    var acc = start;

    for (var i = this.length() - 1; i >= 0; i--) {
      acc = func(this.values[i], acc);
    }

    return acc;
  },

  length: function () {
    var count = 0;
    this.values.forEach(function () { count++; });

    return count;
  },

  reverse: function () {
    return new List(this.foldl(this.cons, []));
  },

  map: function (func, arr) {
    var applyFuncThenCons = function (x, acc) {
      return this.cons(func(x), acc);
    }

    return new List(this.foldr(applyFuncThenCons.bind(this), []));
  },

  filter: function (pred) {
    var consIfPred = function (x, acc) {
      return pred(x) ? this.cons(x, acc) : acc;
    };

    return new List(this.foldr(consIfPred.bind(this), []));
  }
}

module.exports = List;

Version data entries

47 entries across 47 versions & 1 rubygems

Version Path
trackler-2.2.0.4 tracks/javascript/exercises/list-ops/example.js
trackler-2.2.0.3 tracks/javascript/exercises/list-ops/example.js
trackler-2.2.0.2 tracks/javascript/exercises/list-ops/example.js
trackler-2.2.0.1 tracks/javascript/exercises/list-ops/example.js
trackler-2.2.0.0 tracks/javascript/exercises/list-ops/example.js
trackler-2.1.0.55 tracks/javascript/exercises/list-ops/example.js
trackler-2.1.0.54 tracks/javascript/exercises/list-ops/example.js