Skip to content

Instantly share code, notes, and snippets.

@porteron
Created July 30, 2019 05:15
Show Gist options
  • Select an option

  • Save porteron/0939289d1c60467d6fc13d6cb87bebc0 to your computer and use it in GitHub Desktop.

Select an option

Save porteron/0939289d1c60467d6fc13d6cb87bebc0 to your computer and use it in GitHub Desktop.

Revisions

  1. porteron created this gist Jul 30, 2019.
    30 changes: 30 additions & 0 deletions permutations.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    function permutations(word){
    if(word.length <=1) return [word];
    if(typeof word === 'string'){
    word = word.split('')
    }
    if(typeof word === 'number'){
    word = String(word).split('')
    }

    let permutationCollection = [];
    let nextWord = [];
    let characters = [];

    permute(word);

    return permutationCollection

    function permute(characters){
    if(characters.length < 1){
    // add word to permutations array
    permutationCollection.push(nextWord.join(''));
    }
    for(let i = 0; i < characters.length; i++){
    characters.push(characters.shift());
    nextWord.push(characters[0])
    permute(characters.slice(1););
    nextWord.pop();
    }
    }
    }