objectid-random 2.1.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/index.js +17 -5
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -1,16 +1,24 @@
1
- var pads = ['', '0', '00', '000', '0000', '00000', '000000'];
1
+ 'use strict';
2
+
3
+ const pads = ['', '0', '00', '000', '0000', '00000', '000000', '0000000'];
2
4
 
3
5
  function getTime(date) {
4
6
  if (date) {
5
7
  if (typeof date === 'object') {
6
- if (date.toDate) {
8
+ if (typeof date.toDate === 'function') {
7
9
  date = date.toDate();
10
+ if (!(date instanceof Date)) {
11
+ return Date.now() / 1000;
12
+ }
8
13
  }
9
- if (date.getTime) {
14
+ if (typeof date.getTime === 'function') {
10
15
  date = date.getTime();
11
16
  }
12
17
  }
13
18
  if (date && typeof date === 'number') {
19
+ if (date < 0 || date === Infinity) {
20
+ throw new Error('Invalid date');
21
+ }
14
22
  return date / 1000;
15
23
  }
16
24
  }
@@ -18,14 +26,18 @@ function getTime(date) {
18
26
  }
19
27
 
20
28
  function random(date) {
21
- var result = getTime(date).toString(16).replace('.', '').substr(0, 12);
29
+ let [second, millisecond] = getTime(date).toString(16).split('.');
30
+ if (second.length < 8) {
31
+ second = pads[8 - second.length] + second;
32
+ }
33
+ let result = (second + (millisecond || '')).substring(0, 12);
22
34
  if (result.length < 12) {
23
35
  result += pads[12 - result.length];
24
36
  }
25
37
  while (result.length < 24) {
26
38
  result += Math.random()
27
39
  .toString(16)
28
- .substr(2, 24 - result.length);
40
+ .substring(2, 26 - result.length);
29
41
  }
30
42
  return result;
31
43
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "objectid-random",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "Generate random ObjectId like string",
5
5
  "main": "index.js",
6
6
  "scripts": {