Last active
August 29, 2015 13:56
-
-
Save andreypopp/8978374 to your computer and use it in GitHub Desktop.
Array.prototype.filter-like method call expanded into an efficient loop
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
macro replace { | |
case { _ $a:expr $b:expr { $first $rest ... } } => { | |
if ($a.token.value === $first.token.value) { | |
return #{ $b replace $a $b $rest ... } | |
} else { | |
return #{ $first replace $a $b { $rest ... } } | |
} | |
} | |
case { _ $a:expr $b:expr { } } => { | |
return []; | |
} | |
} | |
macro macroFilter { | |
case { _($what:expr, function($arg) { $how ... }) } => { | |
letstx $return = [makeIdent("return", #{$how ...}[0])]; | |
return #{ | |
(function() { | |
let $return = macro { | |
rule { $result:expr } => { | |
if ($result) results.push(cached[i]) | |
continue | |
} | |
} | |
let $arg = macro { | |
rule {} => { cached[i] } | |
} | |
var results = []; | |
var cached = $what; | |
for (var i = 0, len = cached.length; i < len; i++) { | |
$how ... | |
} | |
return results; | |
})(); | |
} | |
} | |
} | |
macro .mfilter { | |
rule infix { $w:expr | ( function($a) { $how ... } ) } => { | |
macroFilter($w, function($a) { $how ... }) | |
} | |
} | |
[1, 2, 3].mfilter(function(item) { | |
if (something) { | |
return false; | |
} | |
item = item + func(item + 2); | |
return !item; | |
}) |
Author
andreypopp
commented
Feb 13, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment