Skip to content

Commit

Permalink
yid
Browse files Browse the repository at this point in the history
  • Loading branch information
Andrew Chilton committed Jan 27, 2018
0 parents commit dd37c2f
Show file tree
Hide file tree
Showing 4 changed files with 112 additions and 0 deletions.
36 changes: 36 additions & 0 deletions ReadMe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# yid #

## Synopsis ##

```js
const yid = require('yid')

console.log(yid())
// -> 1517049989798-7496988299172
```

A `yid`:

* always 27 chars long
* has two parts:
* a timestamp
* a random string
* is of the form `\d{13}-\d{13}`
* starts off with `Date.now()`
* uses `Math.random()` for the second part

## Why? ##

Why another ID generating library?

I already wrote [zid](https://www.npmjs.com/package/zid) and [flake](https://www.npmjs.com/package/flake) (a long time
ago) and they all have uses. The use for this one is to generate FAST but UNIQUE IDs. A secondary property is that they
are approximately sortable across servers.

## Author ##

Andrew Chilton.

## License ##

ISC.
8 changes: 8 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
function yid() {
let id = Date.now() + '-' + String(Math.random()).substr(2, 13)
while ( id.length < 27 )
id += '0'
return id
}

module.exports = yid
22 changes: 22 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "yid",
"version": "1.0.0",
"description": "A small and fast ID generator that produces ordered IDs.",
"main": "index.js",
"scripts": {
"test": "node test.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/chilts/yid.git"
},
"keywords": [
"id"
],
"author": "Andrew Chilton",
"license": "ISC",
"bugs": {
"url": "https://github.com/chilts/yid/issues"
},
"homepage": "https://github.com/chilts/yid#readme"
}
46 changes: 46 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const yid = require('.')

let id
var count = {
'22' : 0,
'23' : 0,
'24' : 0,
'25' : 0,
'26' : 0,
'27' : 0,
'28' : 0,
'29' : 0,
'30' : 0,
'31' : 0,
'32' : 0,
'33' : 0,
'34' : 0,
'35' : 0,
'36' : 0,
'37' : 0,
'38' : 0,
}

for(let i = 0; i < 10000000; i++) {
id = yid()
count['' + id.length]++
}

console.log('count:', count)

if ( count['27'] !== 10000000 ) {
throw new Error("A yid was returned that wasn't 27 chars long")
}

for(let i = 1; i < 1000; i++ ) {
id = yid()

if ( id.split('-').length !== 2 ) {
throw new Error("A yid was returned that didn't have two sections around the dash : " + id)
}

// 1517049989798-7496988299172
if ( !id.match(/^\d{13}-\d{13}$/) ) {
throw new Error("A yid was returned that wasn't of the format DDDDDDDDDDDDD-DDDDDDDDDDDDD : " + id)
}
}

0 comments on commit dd37c2f

Please sign in to comment.