Skip to content

Instantly share code, notes, and snippets.

@kl0tl
Last active August 29, 2015 14:03
Show Gist options
  • Save kl0tl/af6a24bc03a27e171488 to your computer and use it in GitHub Desktop.
Save kl0tl/af6a24bc03a27e171488 to your computer and use it in GitHub Desktop.
Inline `Array#reduce`
macro inline_reduce {
rule { ($list:expr, function ($accumulator:ident, $value:ident, $index:ident, $ref:ident) {
$return:expr
}, $context:expr) } => {
(function ($ref) {
var $accumulator = $ref.shift(), length = $ref.length;
for (var $index = 0; $index < length; $index += 1) {
var $value = $ref[$index];
$accumulator = $return;
}
return $accumulator_symbol;
}.call($context, $list))
}
rule { ($list:expr, function ($accumulator:ident, $value:ident, $index:ident, $ref:ident) {
$return:expr
}, $initial_value:expr, $context:expr) } => {
(function ($ref, $accumulator) {
var length = $ref.length;
for (var $index = 0; $index < length; $index += 1) {
var $value = $ref[$index];
$accumulator = $return;
}
return $accumulator;
}.call($context, $list, $initial_value))
}
}
let reduce = macro {
rule infix { $list:expr . | (() => $return:expr) } => {
inline_reduce($list, function (value, index, ref) { $return }, this)
}
rule infix { $list:expr . | (() => $return:expr, $accumulator:expr) } => {
inline_reduce($list, function (value, index, ref) { $return }, $accumulator, this)
}
rule infix { $list:expr . | ($value:ident => $return:expr) } => {
inline_reduce($list, function ($value, index, ref) { $return }, this)
}
rule infix { $list:expr . | ($value:ident => $return:expr, $accumulator:expr) } => {
inline_reduce($list, function ($value, index, ref) { $return }, $accumulator, this)
}
rule infix { $list:expr . | (($value:ident) => $return:expr) } => {
inline_reduce($list, function ($value, index, ref) { $return }, this)
}
rule infix { $list:expr . | (($value:ident) => $return:expr, $accumulator:expr) } => {
inline_reduce($list, function ($value, index, ref) { $return }, $accumulator, this)
}
rule infix { $list:expr . | (($value:ident, $index:ident) => $return:expr) } => {
inline_reduce($list, function ($value, $index, ref) { $return }, this)
}
rule infix { $list:expr . | (($value:ident, $index:ident) => $return:expr, $accumulator:expr) } => {
inline_reduce($list, function ($value, $index, ref) { $return }, $accumulator, this)
}
rule infix { $list:expr . | (($value:ident, $index:ident, $ref:ident) => $return:expr) } => {
inline_reduce($list, function ($value, $index, $ref) { $return }, this)
}
rule infix { $list:expr . | (($value:ident, $index:ident, $ref:ident) => $return:expr, $accumulator:expr) } => {
inline_reduce($list, function ($value, $index, $ref) { $return }, $accumulator, this)
}
rule { $rest ... } => { reduce $rest ... }
}
export reduceRight;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment