0ad/binaries/data/mods/public/globalscripts/utility.js
elexis 08fbf223f6 Unify random integer and float helper functions of GUI, Simulation and AI.
Patch By: bb
Differential Revision: D121
Refs: #4326

Removes the Random.js simulation helper and randomFloat function of the
random map scripts library.
Adds randomIntInclusive and randomIntExclusive to make the calls more
readable and fix and prevent off-by-one mistakes.
Adds randBool and use it in an AI occurance. It will be used in many
places by the random map scripts.
Use the pickRandom function introduced in 3c56638e8b in more applicable
occurances.
Replace remaining occurances of Math.random() with the new functions to
easily test completeness.

Cleanup of the random map script functions will come in a separate
commit.

This was SVN commit r19270.
2017-03-03 21:13:10 +00:00

46 lines
874 B
JavaScript

/**
* returns a clone of a simple object or array
* Only valid JSON objects are accepted
* So no recursion, and only plain objects or arrays
*/
function clone(o)
{
let r;
if (o instanceof Array)
r = [];
else if (o instanceof Object)
r = {};
else // native data type
return o;
for (let key in o)
r[key] = clone(o[key]);
return r;
}
/**
* "Inside-out" implementation of Fisher-Yates shuffle
*/
function shuffleArray(source)
{
if (!source.length)
return [];
let result = [source[0]];
for (let i = 1; i < source.length; ++i)
{
let j = randIntInclusive(0, i);
result[i] = result[j];
result[j] = source[i];
}
return result;
}
/**
* Removes prefixing path from a path or filename, leaving just the file's name (with extension)
*
* ie. a/b/c/file.ext -> file.ext
*/
function basename(path)
{
return path.slice(path.lastIndexOf("/") + 1);
}