Skip to content

Instantly share code, notes, and snippets.

@andreypopp
Last active August 29, 2015 13:56
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 andreypopp/8978374 to your computer and use it in GitHub Desktop.
Save andreypopp/8978374 to your computer and use it in GitHub Desktop.
Array.prototype.filter-like method call expanded into an efficient loop
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;
})
@andreypopp
Copy link
Author

(function () {
    var results$430 = [];
    var cached$431 = [
            1,
            2,
            3
        ];
    for (var i$432 = 0, len$433 = cached$431.length; i$432 < len$433; i$432++) {
        if (something) {
            if (false)
                results$430.push(cached$431[i$432]);
            continue;
        }
        cached$431[i$432] = cached$431[i$432] + func(cached$431[i$432] + 2);
        if (!cached$431[i$432])
            results$430.push(cached$431[i$432]);
        continue;
    }
    return results$430;
}());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment