Skip to content
Snippets Groups Projects
math.js 1.5 KiB
Newer Older
clemo's avatar
clemo committed
export class Math {
  constructor() {}
  uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
        .replace(/[xy]/g,
                 (c) => {
                   let r = global.Math.random() * 16 | 0,
                       v = c == 'x' ? r : (r & 0x3 | 0x8);
                   return v.toString(16);
                 })
        .toUpperCase();
  }
  checkUuid(uuid) {
    return uuid.search(
               /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i) !==
           -1
  }
clemo's avatar
clemo committed
  random(min, max) {
clemo's avatar
clemo committed
    let MAX_UINT32 = 0xFFFFFFFF;
    let range = max - min;

    if (!(range <= MAX_UINT32)) {
      throw new Error("Range of " + range + " covering " + min + " to " + max +
                      " is > " + MAX_UINT32 + ".");
    } else if (min === max) {
      return min;
    } else if (!(max > min)) {
      throw new Error("max (" + max + ") must be >= min (" + min + ").");
    }

    // We need to cut off values greater than this to avoid bias in distribution
    // over the range.
    let maxUnbiased = MAX_UINT32 - ((MAX_UINT32 + 1) % (range + 1));

    let rand;
    do {
      rand = crypto.getRandomValues(new Uint32Array(1))[0];
    } while (rand > maxUnbiased);

    let offset = rand % (range + 1);
    return min + offset;
  }
  uniqueRandomArray(amount, from, to) {
    let found = [];
    while (found < amount) {
      let r = this.random(from, to);
      if (found.indexOf(r) === -1) {
        found.push(r);
      }
    }
    return found;
  }
}
exports.default = Math;