Skip to content

Instantly share code, notes, and snippets.

@torifat
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torifat/a88c5b2309e7b71068ea to your computer and use it in GitHub Desktop.
Save torifat/a88c5b2309e7b71068ea to your computer and use it in GitHub Desktop.
List.js
// TODO: Add Validations
var List = function (value) {
this.value = value || [];
};
List.prototype.unit = function (value) {
return new List(value);
};
List.prototype.flatMap = function (fn, context) {
var results = [];
this.value.forEach(function (value, key, map) {
var ret = fn.call(context, value, key, map);
if (ret instanceof List) {
ret = ret.get();
}
if (Array.isArray(ret)) {
[].push.apply(results, ret);
}
else if (ret) {
results.push(ret);
}
});
return new List(results);
};
List.prototype.get = function () {
return this.value;
};
List.prototype.map = function (fn) {
return this.flatMap(function (x) {
return this.unit(fn(x));
}, this);
};
List.prototype.filter = function (fn) {
return this.flatMap(function (x) {
return fn(x) ? this.unit(x) : null;
}, this);
};
List.prototype.filterNot = function (fn) {
return this.flatMap(function (x) {
return fn(x) ? null : this.unit(x);
}, this);
};
var l = new List([1, 2, 3]);
var fn = function (val) {
return [val, val*2, val*3];
};
var double = function (val) {
return val * 2;
};
var even = function (val) {
return val % 2 === 0;
};
console.log(l.flatMap(fn).get());
console.log(l.map(double).get());
console.log(l.filterNot(even).get());
console.log(l.filterNot(even).map(double).get());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment