Name Shortener

by dmazza

HTML

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<div class="container-fluid">
    <div class="row-fluid">
<div class="span12">
    <legend>Name Shortener</legend>
</div>
<form class="well span12">
    <div><label>Length</label> <input type="number" id="length" value="3" /></div>
    <div><label>Name</label> <input type="text" placeholder="start typing to see results" id="original" /></div>
    <div>
    <ul id="output" class="nav nav-tabs nav-stacked">
    </ul>
    </div>
</form>
</div>
</div>

JavaScript

// Project: Name Shortener
// Author: David Mazza, @dmazza, http://github.com/dmazza
// Legalese: MIT License (see below)

var original = '', length = 0, output = "";
$("#original").on("keyup", function() { gen(); });
$("#length").on("change", function() { gen(); });

var gen = function() {
    //reset variables
    original = $("#original").val();
    length = $("#length").val();
    output = "";
    //clear the output
    $("#output").html("");
    //run the recursive character stripping function on the original name
    strip("", original);
    //put the results in the output div
    $("#output").html("<div class='alert alert-info'>Click on the ones you like to highlight them</div>" + output);
    $("a").on("click", function() { $(this).parent().toggleClass("active"); });
};

var strip = function(front, input) {
    //base cases:
    //if the front of the result is longer than the desired output, then skip
    //if the front combined with the input is the right length, the add it to the output
    if(front.length <= length) {
        if((front.length + input.length) == length) {
            output = output + "<li><a>" + front + input + "</a></li>";
        } else {
            //for each character in the input
            for(var i = 0; i < input.length; i++) {
                //add characters 0-i to the front, and make the recursive call with characters i+1 to the end of the string as input
                strip(front + input.substring(0,i), input.substring(i+1, input.length));        
            }
        }
    }
}
    
//On input 'abcd' for a length of 2
//The algorithm would run like this:   
    // front input => output
    //       abcd
    //       bcd
    //       cd    => cd
    // b     d     => bd
    // b     c     => bc
    // bcd            too long
    // a     cd
    // a     d     => ad
    // a     c     => ac
    // ab    d
    // ab          => ab
    // abc            too...