Skip to content

Commit

Permalink
Add ability to convert a yid ID back to a Date
Browse files Browse the repository at this point in the history
  • Loading branch information
chilts committed Apr 17, 2020
1 parent 4bca749 commit b6aaf28
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
10 changes: 10 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,14 @@ function yid() {
return id
}

function toDate(id) {
if ( !id.match(/^\d{13}-\d{13}$/) ) {
throw new Error(`Format of id is incorrect: ${id}`)
}
const epoch = id.split('-')[0]
return new Date(Number(epoch))
}

yid.toDate = toDate

module.exports = yid
23 changes: 18 additions & 5 deletions test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const yid = require('.')

let id
var count = {
// setup
const times = 1000000
const count = {
'22' : 0,
'23' : 0,
'24' : 0,
Expand All @@ -21,18 +22,30 @@ var count = {
'38' : 0,
}

for(let i = 0; i < 10000000; i++) {
// tests
let id = ''

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

// check we can get the date back
const d = yid.toDate(id)
if (!(d instanceof Date)) {
throw new Error("toDate() returned something that wasn't a date!")
}
if (String(d.valueOf()) != id.split('-')[0]) {
throw new Error("the date's epoch (d.valueOf()) didn't match the epoch of the id")
}
}

console.log('count:', count)

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

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

if ( id.split('-').length !== 2 ) {
Expand Down

0 comments on commit b6aaf28

Please sign in to comment.