Last active
August 29, 2015 14:10
-
-
Save ahmetkakici/ae3ead094b10e91da222 to your computer and use it in GitHub Desktop.
query js arrays with lambda expressions. i love them.
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
Array.prototype.where = | |
function (f) { | |
var fn = f; | |
if (typeof f == "string") | |
if (( fn = lambda(fn) ) == null) | |
throw "Syntax error in lambda string: " + f; | |
var res = []; | |
var l = this.length; | |
var p = [0, 0, res]; | |
for (var i = 1; i < arguments.length; i++) p.push(arguments[i]); | |
for (var i = 0; i < l; i++) { | |
if (typeof this[i] == "undefined") continue; | |
p[0] = this[i]; | |
p[1] = i; | |
if (!!fn.apply(this, p)) res.push(this[i]); | |
} | |
return res; | |
}; | |
function lambda(l) { | |
var fn = l.match(/\((.*)\)\s*=>\s*(.*)/); | |
var p = []; | |
var b = ""; | |
if (fn.length > 0) fn.shift(); | |
if (fn.length > 0) b = fn.pop(); | |
if (fn.length > 0) p = fn.pop() | |
.replace(/^\s*|\s(?=\s)|\s*$|,/g, '').split(' '); | |
// prepend a return if not already there. | |
fn = ( ( !/\s*return\s+/.test(b) ) ? "return " : "" ) + b; | |
p.push(fn); | |
try { | |
return Function.apply({}, p); | |
} | |
catch (e) { | |
return null; | |
} | |
} | |
///jsonData.data.where("( el, i, res, param ) => el.plan_type == param", record[0].raw.name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment