Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
regex fall-throughs using a switch(true), inspired by @AvianFlu
substack : ~ $ node switch.js bleep blah
blah
substack : ~ $ node switch.js for the lose
lose
substack : ~ $ node switch.js for the win
win
substack : ~ $ node switch.js for the fail
fail
substack : ~ $
var m, s = process.argv.slice(2).join(' ');
switch (true) {
case Boolean(m = s.match(/fail/)) :
console.log('fail');
break;
case Boolean(m = s.match(/for the (\S+)/)) :
console.log(m[1]);
break;
case Boolean(m = s.match(/blah/)) :
console.log('blah');
break;
}
@tilgovi

This comment has been minimized.

Copy link

tilgovi commented Oct 4, 2011

Nice trick!

@jfhbrook

This comment has been minimized.

Copy link

jfhbrook commented Oct 5, 2011

I'll have to remember this one.

@tilgovi

This comment has been minimized.

Copy link

tilgovi commented Oct 5, 2011

I was just yesterday saying how it'd be neat if regex could be used to pattern match or guard in erlang case statements.

@mattryall

This comment has been minimized.

Copy link

mattryall commented Oct 17, 2011

What does this add over just using an if/else block? The switch(true) {...} and Boolean() wrapping seem redundant to me.

Simpler version: https://gist.github.com/1292030

@tilgovi

This comment has been minimized.

Copy link

tilgovi commented Oct 17, 2011

@mattryall: radness

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.