Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling words in a sentence in javascript (coding horror - How to improve?)

I'm trying to do something that is fairly simple, but my code looks terrible and I am certain there is a better way to do things in javascript. I am new to javascript, and am trying to improve my coding. This just feels very messy.

All I want to do is to randomly change the order some words on a web page. In python, the code would look something like this:

s = 'THis is a sentence'
shuffledSentence = random.shuffle(s.split(' ')).join(' ')

However, this is the monstrosity I've managed to produce in javascript

//need custom sorting function because javascript doesn't have shuffle?
function mySort(a,b) {    
    return a.sortValue - b.sortValue;
}

function scrambleWords() {

    var content = $.trim($(this).contents().text());

    splitContent = content.split(' ');

    //need to create a temporary array of objects to make sorting easier
    var tempArray = new Array(splitContent.length);

    for (var i = 0; i < splitContent.length; i++) {
        //create an object that can be assigned a random number for sorting
        var tmpObj = new Object();
        tmpObj.sortValue = Math.random();
        tmpObj.string = splitContent[i];
        tempArray[i] = tmpObj;       
    }

    tempArray.sort(mySort);

    //copy the strings back to the original array
    for (i = 0; i < splitContent.length; i++) {
        splitContent[i] = tempArray[i].string;
    }

    content = splitContent.join(' ');       
    //the result
    $(this).text(content);      

}

Can you help me to simplify things?

like image 301
Bill Zimmerman Avatar asked Apr 27 '10 19:04

Bill Zimmerman


3 Answers

Almost similar to the python code:

var s = 'This is a sentence'
var shuffledSentence = s.split(' ').shuffle().join(' ');

For the above to work, we need to add a shuffle method to Array (using Fisher-Yates).

Array.prototype.shuffle = function() {
    var i = this.length;
    if (i == 0) return this;
    while (--i) {
        var j = Math.floor(Math.random() * (i + 1 ));
        var a = this[i];
        var b = this[j];
        this[i] = b;
        this[j] = a;
    }
    return this;
};
like image 146
Anurag Avatar answered Oct 21 '22 01:10

Anurag


String.prototype.shuffler=function(delim){
    delim=delim || '';
    return this.split(delim).sort(function(){
            return .5-Math.random()}).join(delim);
}

// to shuffle words, pass a space

var s='abc def ghi jkl mno pqr stu vwx yz' alert(s.shuffler(' '))

like image 25
kennebec Avatar answered Oct 21 '22 02:10

kennebec


This is very old question but can still be useful.
Here is a very easy way to do it using array.sort()

const s = 'This is very old question but can still be useful.';

console.log(s.split(' ').sort(() => Math.floor(Math.random() * Math.floor(3)) - 1).join(' '))
like image 33
ben Avatar answered Oct 21 '22 01:10

ben