Skip to content

Instantly share code, notes, and snippets.

@kl0tl
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save kl0tl/e33e996e4561d4641b31 to your computer and use it in GitHub Desktop.

Select an option

Save kl0tl/e33e996e4561d4641b31 to your computer and use it in GitHub Desktop.
Inline `Array#reduceRight`
macro inline_reduceRight {
rule { ($list:expr, function ($accumulator:ident, $value:ident, $index:ident, $ref:ident) {
$return:expr
}, $context:expr) } => {
(function ($ref) {
var $accumulator = $ref.pop();
for (var $index = $ref.length - 1; $index > -1; $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) {
for (var $index = $ref.length - 1; $index > -1; $index -= 1) {
var $value = $ref[$index];
$accumulator = $return;
}
return $accumulator;
}.call($context, $list, $initial_value))
}
}
let reduceRight = macro {
rule infix { $list:expr . | (() => $return:expr) } => {
inline_reduceRight($list, function (value, index, ref) { $return }, this)
}
rule infix { $list:expr . | (() => $return:expr, $accumulator:expr) } => {
inline_reduceRight($list, function (value, index, ref) { $return }, $accumulator, this)
}
rule infix { $list:expr . | ($value:ident => $return:expr) } => {
inline_reduceRight($list, function ($value, index, ref) { $return }, this)
}
rule infix { $list:expr . | ($value:ident => $return:expr, $accumulator:expr) } => {
inline_reduceRight($list, function ($value, index, ref) { $return }, $accumulator, this)
}
rule infix { $list:expr . | (($value:ident) => $return:expr) } => {
inline_reduceRight($list, function ($value, index, ref) { $return }, this)
}
rule infix { $list:expr . | (($value:ident) => $return:expr, $accumulator:expr) } => {
inline_reduceRight($list, function ($value, index, ref) { $return }, $accumulator, this)
}
rule infix { $list:expr . | (($value:ident, $index:ident) => $return:expr) } => {
inline_reduceRight($list, function ($value, $index, ref) { $return }, this)
}
rule infix { $list:expr . | (($value:ident, $index:ident) => $return:expr, $accumulator:expr) } => {
inline_reduceRight($list, function ($value, $index, ref) { $return }, $accumulator, this)
}
rule infix { $list:expr . | (($value:ident, $index:ident, $ref:ident) => $return:expr) } => {
inline_reduceRight($list, function ($value, $index, $ref) { $return }, this)
}
rule infix { $list:expr . | (($value:ident, $index:ident, $ref:ident) => $return:expr, $accumulator:expr) } => {
inline_reduceRight($list, function ($value, $index, $ref) { $return }, $accumulator, this)
}
rule { $rest ... } => { reduceRight $rest ... }
}
export reduceRight;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment