String Permutations

Write a program to print out all the permutations of a string in alphabetical order.

by Donal Devine

HTML

<div id="div1"></id>

JavaScript

var foo = function(str) {

    Array.prototype.getUnique = function(){
        var u = {}, a = [];
        for(var i = 0, l = this.length; i < l; ++i){
            if(u.hasOwnProperty(this[i])) {
                continue;
            }
            a.push(this[i]);
            u[this[i]] = 1;
        }
        return a;
    };

    function bar(str, prefix) {
        if (str.length === 0) {
            return [prefix];
        } else {
            var out = [];
            for (var i = 0; i < str.length; i++) {
                var pre = str.substr(0, i);
                var post = str.substr(i + 1);
                out = out.concat(bar(pre + post, str[i] + prefix));
            }
            return out;
        }
    }

    var out = bar(str, "");

    return out.getUnique().sort().join(",");
};

var result = foo("hat");
div1.innerHTML="<h1>" + result + "</h1>";