Javascript String scramble()

Description

Javascript String scramble()

String.prototype.scramble = function () {
  var stringArr = this.split('');
  var tmpArr = [];
  
  function rndIntInRange (range) {
    return Math.floor(Math.random()*range);
  }/*from w  w  w . j  ava2s  . c o m*/

  while (stringArr.length > 0){
    var cutChar = stringArr.splice(rndIntInRange(stringArr.length),1);
    tmpArr.push(cutChar);
  }

  return tmpArr.join('');

};

Javascript String scramble()

var HALFSIES = 0.5;

String.prototype.scramble = function() {
  var string_array = this.split("");

  // calling sort with a random comparison function.  this makes it swap
  // half of the time.
  string_array.sort(function() {return (Math.random() > HALFSIES) } );
  return string_array.join("");
}



PreviousNext

Related