Skip to content

Instantly share code, notes, and snippets.

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