uuid_v4.js

const cryptoBytes = require('crypto').randomBytes

/**
 * It does only one thing - generate <a href="https://tools.ietf.org/html/rfc4122">UUIDv4</a>
 */
class UUIDv4 {
  constructor () {
    this._byteToHex = []
    for (let i = 0; i < 256; i++) {
      this._byteToHex[i] = (i + 0x100).toString(16).substr(1)
    }
  }

  /**
   * @returns {string} the UUID v4
   */
  generate () {
    let i = 0
    const randoms = cryptoBytes(16)
    randoms[6] = (randoms[6] & 0x0f) | 0x40
    randoms[8] = (randoms[8] & 0x3f) | 0x80

    return this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] + '-' +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] + '-' +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] + '-' +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] + '-' +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]] +
      this._byteToHex[randoms[i++]]
  }
}

module.exports = UUIDv4