Skip to content

Instantly share code, notes, and snippets.

@ozten
Forked from disnet/gist:6024991
Created June 10, 2014 21:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozten/f4a23d85e49a628c4a35 to your computer and use it in GitHub Desktop.
Save ozten/f4a23d85e49a628c4a35 to your computer and use it in GitHub Desktop.
macro _arms {
rule {(default => $value:expr)} => {
else {
return $value;
}
}
rule {(rule {$cond:expr} => $value:expr)} => {
if($cond) {
return $value;
}
}
rule {(
$(rule {$cond:expr} => $value:expr) $rest ...
)} => {
_arms (rule {$cond} => $value)
_arms ($rest ...)
}
}
macro cond {
rule {{ $arms ... }} => {
(function() {
_arms($arms ...)
})();
}
}
var x = [];
var type = cond {
rule {(x === null)} => "null"
rule {Array.isArray(x)} => "array"
rule {(typeof x === "object")} => "object"
default => typeof x
}
@trxcllnt
Copy link

This can also expand nicely to a nested ternary:

macro cond {
    rule { {case { } => $value:expr} } => {
        $value;
    }
    rule { {case {$cond:expr} => $value:expr $rest ...} } => {
        ($cond) ? $value : cond { $rest ... }
    }
}

var x2 = [], type2 = cond {
    case { x2 === null } => "null"
    case { Array.isArray(x2) } => "array"
    case { typeof x2 === "object" } => "object"
    case { } => typeof x2
}
// var x2 = [], type2 = x2 === null ? 'null' : Array.isArray(x2) ? 'array' : typeof x2 === 'object' ? 'object' : typeof x2;

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