Nodejs String Shuffle shuffle()

Here you can find the source of shuffle()

Method Source Code

/**/*ww w  .j  a va  2 s .  com*/
 * Shuffle the string
 */
String.prototype.shuffle = function () {
   var a = this.split(""),
      n = a.length;

   for(var i = n - 1; i > 0; i--) {
      var j = Math.floor(Math.random() * (i + 1));
      var tmp = a[i];
      a[i] = a[j];
      a[j] = tmp;
   }

   return a.join("");
}

/**
 * Create a new Document
 */
function createNewDocument() {
   // Create a soup to pull from
   var soup = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
      documentId = "",
      length = 6;
   
   // Shuffle the soup
   soup = soup.shuffle();

   // Loop until you have a sufficiently long string
   while( documentId.length < length ) {
      // Create a position
      var pos = Math.floor( Math.random() * soup.length ) + 1

      // Append the document id
      documentId += soup.charAt( pos );
   }

   // Redirect to the new location
   window.location.href = "/edit/" + documentId;
};

Related

  1. shuffle()
    String.prototype.shuffle = function ()
        var characters = this.split(''),
            iterations = (characters.length-1),
            i, j, tmp;
        for (i = iterations; i > 0; i--) {
            j = Math.floor(Math.random() * (i + 1));
            tmp = characters[i];
            characters[i] = characters[j];
    ...
    
  2. shuffle()
    'use strict';
    String.prototype.shuffle = function () {
        var array = this.split('');
        for(var i = array.length - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var holder = array[i];
            array[i] = array[j];
            array[j] = holder;
        return array.join('');
    };
    
  3. shuffle()
    String.prototype.shuffle = function () {
        var array = this.split('');
        var tmp, current, top = array.length;
        if (top) while (--top) {
            current = Math.floor(Math.random() * (top + 1));
            tmp = array[current];
            array[current] = array[top];
            array[top] = tmp;
        return array.join('');
    };
    
  4. shuffle()
    String.prototype.shuffle = function() {
        var arr = this.arrayise();
        for (var i = arr.length - 1; i > 0; i--) {
            var randIndex = Math.floor(Math.random() * (i + 1));
            var temp = arr[i];
            arr[i] = arr[randIndex];
            arr[randIndex] = temp;
        return arr.join('');
    ...