Skip to content

Instantly share code, notes, and snippets.

@tylerbuchea
Created April 20, 2013 01:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tylerbuchea/5424291 to your computer and use it in GitHub Desktop.
Save tylerbuchea/5424291 to your computer and use it in GitHub Desktop.
All possible combinations of a string.
function combinations(str) {
var fn = function(active, rest, a) {
if (!active && !rest)
return;
if (!rest) {
a.push(active);
} else {
fn(active + rest[0], rest.slice(1), a);
fn(active, rest.slice(1), a);
}
return a;
}
return fn("", str, []);
}
/*
usage: combinations("abcd")
output: ["abcd", "abc", "abd", "ab", "acd", "ac", "ad", "a", "bcd", "bc", "bd", "b", "cd", "c", "d"]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment