Skip to content

Instantly share code, notes, and snippets.

@kulturpessimist
Created October 1, 2019 21:44
Show Gist options
  • Save kulturpessimist/944e04ce9fe7db5d91faf5071a3e52c6 to your computer and use it in GitHub Desktop.
Save kulturpessimist/944e04ce9fe7db5d91faf5071a3e52c6 to your computer and use it in GitHub Desktop.
const id = Helper.generateUnified(179); // generate tracking ID for customer 179
console.log( id )
> ZQA-179-946629
const Helper = {
_leftPad (i, n, pad) {
return Array(n - String(i).length + 1).join(pad || '0') + i
},
// UUID Helper from https://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
uuid () {
const prefix = arguments[0] || ''
return (
prefix +
'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
const r = (Math.random() * 16) | 0
const v = c === 'x' ? r : (r & 0x3) | 0x8
return v.toString(16)
})
)
},
// tracking
lastId: ' ',
hash (text) {
let hash = 5381
let index = text.length
while (index) {
hash = (hash * 33) ^ text.charCodeAt(--index)
}
return hash >>> 0
},
optimize (number) {
// convert the base10 number to a short base32 number in uppercase
let resp = parseInt(number, 10)
.toString(32)
.toUpperCase() /// ... and replace the missleading chars
resp = resp.replace('I', 'Z')
resp = resp.replace('O', 'Y')
resp = resp.replace('0', 'X')
// letter W is still unused
return resp
},
beat () {
// generate the beat with the desired resolution
const resolution = arguments[0] || 1000
const beat = Math.round(((new Date() / 864e2 + 1e3 / 24) % 1e3) * resolution)
return beat
},
day () {
// generate day of the year with leading zeros
const day =
(Date.UTC(new Date().getFullYear(), new Date().getMonth(), new Date().getDate()) -
Date.UTC(new Date().getFullYear(), 0, 0)) /
24 /
60 /
60 /
1000
return this._leftPad(day, 2, 0)
},
generateClientHash (name) {
const hash = this.optimize(this.hash(name))
return this._leftPad(hash, 7, 0)
},
generateUnified () {
const tag = arguments[0] || '000' // tag is the customer id if no tag is given we take 000
const shortYear = new Date()
.getFullYear()
.toString()
.substring(2)
const day = this.day()
const seq = this.beat(1000)
this.lastId = [
this.optimize(shortYear.toString() + day.toString()), // first segment is the short year+day
tag, // second segment is the customer ID or a custom tag
seq // last segment is the count in milli-beat time (swatch internet time ^1000)
].join('-') // joined by simple "minus " signs
return this.lastId
}
}
export default Helper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment