All files / src timestampGetter.ts

100% Statements 31/31
100% Branches 12/12
100% Functions 1/1
100% Lines 30/30
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 713x 3x     3x     3x     3x     3x     3x       3x         18x 1x       17x 5x 5x 5x 12x   8x 2x     6x   6x   6x   6x 6x 6x 4x 3x     1x       15x 15x               15x     3x  
import bigInt from 'big-integer';
import {
  convertBinStrToUint8Array,
} from './convertBinStrToUint8Array';
import {
  getHundredsOfNanosecondsSinceGregorianReform,
} from './getHundredsOfNanosecondsSinceGregorianReform';
import {
  isUUIDVersion,
} from './TypeGuards/isUUIDVersion';
import {
  randomBytesGenerator,
} from './randomBytesGenerator';
import {
  strings,
} from './strings';
import {
  UUIDVersions,
} from './Enums/UUIDVersions';
 
export const timestampGetter = (
  version: UUIDVersions,
  hash?: string,
): Uint8Array =>
{
  if (!isUUIDVersion(version)) {
    throw new Error(strings.UUID_VERSION_INVALID);
  }
 
  let timestamp: Uint8Array;
  if (version === UUIDVersions.One) {
    const currentTimestamp = getHundredsOfNanosecondsSinceGregorianReform();
    const timestampStr = currentTimestamp.toString(2);
    timestamp = convertBinStrToUint8Array(timestampStr);
  } else if (version === UUIDVersions.Three || version === UUIDVersions.Five) {
    /* Version is 3 or 5. */
    if (!hash) {
      throw new Error(strings.HASH_ARGUMENT_MISSING);
    }
 
    let timestampStr = '';
    /* time_low */
    timestampStr = hash.slice(0, 8);
    /* time_mid */
    timestampStr = hash.slice(8, 12) + timestampStr;
    /* time_hi */
    timestampStr = hash.slice(12, 16) + timestampStr;console.log(timestampStr)
    const timestampBinStr = bigInt(timestampStr, 16).toString(2);
    timestamp = convertBinStrToUint8Array(timestampBinStr);
  } else if (version === UUIDVersions.Four) {
    timestamp = randomBytesGenerator(8);
  } else {
    /* Version is nil. */
    timestamp = new Uint8Array([ 0, 0, 0, 0, 0, 0, 0, 0, ]);
  }
 
  /* Clamp the result to 60 bits. */
  timestamp[0] = Math.min(32, timestamp[0]);
  timestamp = new Uint8Array(
    /* Fill missing most-significant with 0s. */
    '0'.repeat(8 - timestamp.length)
      .split('')
      .map(parseInt)
      .concat(Array.prototype.slice.call(timestamp))
  );
 
  return timestamp;
}
 
export default timestampGetter;