// To run with node: npm install lodash && node perms.js star var _ = require('lodash'), words = ['stars']; function getPermutations(word) { // Stop case for single character if (word.length === 1) { return [word]; } // For each letter... return _.reduce(word, function (result, letter, idx) { // Grab the other letters var rest = [word.slice(0, idx), word.slice(idx + 1)].join(''), // Get all permutations of the other letters to the right rightCombos = getPermutations(rest); // For each right combo, add the current letter onto it and // push into result _.each(rightCombos, function (combo) { result.push(letter + combo); }); // Return the aggregated results from all letter combinations return result; }, []); } // Allow passing in words to do if (process.argv.length > 2) { words = process.argv.slice(2); } _.each(words, function (word) { var perms = _.unique(getPermutations(word)), title = word + ' (' + perms.length + ')'; console.log(title); console.log(new Array(title.length + 1).join('=')); _.each(perms, function (perm) { console.log(perm); }); console.log(''); });