Last active
August 29, 2015 14:05
-
-
Save torifat/a88c5b2309e7b71068ea to your computer and use it in GitHub Desktop.
List.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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