Skip to content

Instantly share code, notes, and snippets.

@kl0tl
Created June 29, 2014 16:44
Show Gist options
  • Save kl0tl/abd6046271bb56344505 to your computer and use it in GitHub Desktop.
Save kl0tl/abd6046271bb56344505 to your computer and use it in GitHub Desktop.
Inline `Array.from`
macro inline_from {
rule { ($constructor:expr, $list:expr, function ($value:ident, $index:ident, $ref:ident) {
$return:expr
}, $context:expr) } => {
(function (constructor, ref) {
var length = ref.length, res = new constructor(length);
for (var $index = 0; $index < length; $index += 1) {
var $value = ref[$index];
res[$index] = $return;
}
return res;
}.call($context, $constructor, $list));
}
}
let from = macro {
rule infix { $symbol:ident (.) ... $constructor:ident . | ($list:expr, () => $return:expr) } => {
inline_from($symbol (.) ... $constructor, $list, function (value, index, ref) { $return }, this)
}
rule infix { $constructor:expr . | ($list:expr, () => $return:expr) } => {
inline_from($constructor, $list, function (value, index, ref) { $return }, this)
}
rule infix { $symbol:ident (.) ... $constructor:ident . | ($list:expr, $value:ident => $return:expr) } => {
inline_from($symbol (.) ... $constructor, $list, function ($value, index, ref) { $return }, this)
}
rule infix { $constructor:expr . | ($list:expr, $value:ident => $return:expr) } => {
inline_from($constructor, $list, function ($value, index, ref) { $return }, this)
}
rule infix { $symbol:ident (.) ... $constructor:ident . | ($list:expr, ($value:ident) => $return:expr) } => {
inline_from($symbol (.) ... $constructor, $list, function ($value, index, ref) { $return }, this)
}
rule infix { $constructor:ident . | ($list:expr, ($value:ident) => $return:expr) } => {
inline_from($constructor, $list, function ($value, index, ref) { $return }, this)
}
rule infix { $symbol:ident (.) ... $constructor:ident . | ($list:expr, ($value:ident, $index:ident) => $return:expr) } => {
inline_from($symbol (.) ... $constructor, $list, function ($value, $index, ref) { $return }, this)
}
rule infix { $constructor:expr . | ($list:expr, ($value:ident, $index:ident) => $return:expr) } => {
inline_from($constructor, $list, function ($value, $index, ref) { $return }, this)
}
rule { $rest ... } => { from $rest ... }
}
export from;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment