Javascriptはcuidの一意の標識番号を実現します.

18652 ワード

常用cuid.jsの実現
function pad (num, size) {
     
    var s = '000000000' + num;
    return s.substr(s.length - size);
};

var os = require('os'),
    padding = 2,
    pid = pad(process.pid.toString(36), padding),
    hostname = os.hostname(),
    length = hostname.length,
    hostId = pad(hostname
      .split('')
      .reduce(function (prev, char) {
     
        return +prev + char.charCodeAt(0);
      }, +length + 36)
      .toString(36),
    padding);

function fingerprint () {
     
  return pid + hostId;
};

var lim = Math.pow(2, 32) - 1;

function random () {
     
  return Math.abs(require('crypto').randomBytes(4)
    .readInt32BE() / lim);
};

var c = 0,
  blockSize = 4,
  base = 36,
  discreteValues = Math.pow(base, blockSize);

function randomBlock () {
     
  return pad((random() *
    discreteValues << 0)
    .toString(base), blockSize);
}

function safeCounter () {
     
  c = c < discreteValues ? c : 0;
  c++; // this is not subliminal
  return c - 1;
}

function cuid () {
     
  // Starting with a lowercase letter makes
  // it HTML element ID friendly.
  var letter = 'c', // hard-coded allows for sequential access

    // timestamp
    // warning: this exposes the exact date and time
    // that the uid was created.
    timestamp = (new Date().getTime()).toString(base),

    // Prevent same-machine collisions.
    counter = pad(safeCounter().toString(base), blockSize),

    // A few chars to generate distinct ids for different
    // clients (so different computers are far less
    // likely to generate the same id)
    print = fingerprint(),

    // Grab some more chars from Math.random()
    random = randomBlock() + randomBlock();

  return letter + timestamp + counter + print + random;
}

cuid.slug = function slug () {
     
  var date = new Date().getTime().toString(36),
    counter = safeCounter().toString(36).slice(-4),
    print = fingerprint().slice(0, 1) +
      fingerprint().slice(-1),
    random = randomBlock().slice(-2);

  return date.slice(-2) +
    counter + print + random;
};

cuid.isCuid = function isCuid (stringToCheck) {
     
  if (typeof stringToCheck !== 'string') return false;
  if (stringToCheck.startsWith('c')) return true;
  return false;
};

cuid.isSlug = function isSlug (stringToCheck) {
     
  if (typeof stringToCheck !== 'string') return false;
  var stringLength = stringToCheck.length;
  if (stringLength >= 7 && stringLength <= 10) return true;
  return false;
};

cuid.fingerprint = fingerprint;