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

I'm trying to make something pretty simple, but my code looks awful, and I'm sure there is a better way to do something in javascript. I am new to javascript and I am trying to improve my encoding. It is just very unpleasant.

All I want to do is randomly reorder 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 a monster that I managed to create 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 simplify things?

+3
source share
4 answers

Almost similar to python code:

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

Shuffle Array ( 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;
};
+11
String.prototype.shuffler=function(delim){
    delim=delim || '';
    return this.split(delim).sort(function(){
            return .5-Math.random()}).join(delim);
}

// ,

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

+1

, :

function scrambleWords(text) {
  var words = text.split(' ');
  var result = "";

  while(words.length > 0) {
    if(result.length > 0) { words += " "; }
    words += words.splice(Math.abs(Math.random() * (words.length - 1)), 1);
  }

  return result;
}

, .

: ( ), , , , , .

UPDATE: , , : D

0

, . , 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(' '))
Hide result
0
source

Source: https://habr.com/ru/post/1743058/


All Articles