Skip to content
Snippets Groups Projects
math.js 1.17 KiB
Newer Older
clemo's avatar
clemo committed
import crypto from 'crypto';
clemo's avatar
clemo committed
/** math functions*/
clemo's avatar
clemo committed
export class Math {
clemo's avatar
clemo committed

clemo's avatar
clemo committed
  constructor() {}
clemo's avatar
clemo committed
  /** will generate uuid*/
clemo's avatar
clemo committed
  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();
  }
clemo's avatar
clemo committed
  /** will check a uuid - if uuid*/
clemo's avatar
clemo committed
  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
  /** get random value between min(inclusive) & max(inclusive)*/
clemo's avatar
clemo committed
  random(min, max) {
clemo's avatar
clemo committed
    return global.Math.floor(min + (global.Math.random() * (max + 1 - min)));
    // return min + offset;
clemo's avatar
clemo committed
  }
clemo's avatar
clemo committed
  /** fill a array with random values unique to the array*/
clemo's avatar
clemo committed
  uniqueRandomArray(amount, from, to) {
clemo's avatar
clemo committed
    if (amount > to - from) {
      return [];
    }
clemo's avatar
clemo committed
    let found = [];
clemo's avatar
clemo committed
    while (found.length < amount) {
clemo's avatar
clemo committed
      let r = this.random(from, to);
      if (found.indexOf(r) === -1) {
        found.push(r);
      }
    }
    return found;
  }
}
exports.default = Math;