JavaScript Tips and Tricks by Mario Dcunha.


Index


Random

Using random() generates a "float" value or "decimal".
So you will need to use Math.floor all the time, to get a "whole number".

Tip to have simpler code, by using parameters:

function myRandom(num)
{
   return Math.floor(random(num));
}

Now use myRandom(yourNumberRange) to generate your "random whole numbers" with no worry of decimals.


Random and Arrays

Extending Random to arrays, can give you many possibilities.
Every array, has an array index, array[arrayIndex].

You can randomize the arrayIndex, by using array[myRandom(num)] and the num can be the array.length

You could also use shuffle() functions for the array and increase the degree of randomness.

Adding more elements of 'crazy' or 'OCD', you can create arrays of let's say some indexes - for example:

If you're array has 20 elements - you can use this master array as, literally an 'Index' - like the index page in a book, and create the sub-arrays to organise these elements.

We can make sub-arrays like sub1 = [0, 4, 8, 1, 9] and sub2 = [1, 2, 3, 5, 10, 13...], and then jumble and play around with these.

We can look at the above example, as a semi-non-procedural way, creating procedural randomness - whatever that means.

Take a look at the below example function. This gives a random element from an array. Figure out how that works. Change the values inside, take a dummy array, try it out.

function arrayRandom(myArray)
{
   return myArray[Math.floor(random(myArray.length))];
}


"RandomNoise"

RandomNoise is a quick funciton framework which I came up with to just undertand and toggle between random(), noise() and using both together. Click for more.