Skip to content

Instantly share code, notes, and snippets.

@117
Created July 6, 2021 00:38
Show Gist options
  • Save 117/12c3ad2381b0a4d557a14a31dbb423d5 to your computer and use it in GitHub Desktop.
Save 117/12c3ad2381b0a4d557a14a31dbb423d5 to your computer and use it in GitHub Desktop.
import crypto from 'crypto'
// WARNING: DO NOT CHANGE THESE WITH OPEN POSITIONS
const PREFIX = 'X'
const CHARSET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ'
const RANDOM_LENGTH = 16
const EXPRESSION = new RegExp(`^${PREFIX}-[0-9A-Z]{${RANDOM_LENGTH}}-\\d+$`)
// UNIQ-SEQ
export class PositionId {
public uniq: string
public seq: number
constructor(public value: string) {
if (!PositionId.match(value)) {
throw 'value does not look like a PositionId'
}
let [prefix, rand, seq] = this.value.split('-')
this.uniq = `${prefix}-${rand}`
this.seq = parseInt(seq)
}
inc() {
++this.seq
return this
}
eq(value: string) {
return value.includes(this.uniq)
}
toString() {
return `${this.uniq}-${this.seq}`
}
static match(value: string) {
return value.match(EXPRESSION)
}
static gen() {
return `${PREFIX}-${new Array(RANDOM_LENGTH)
.fill(null)
.map(() => CHARSET.charAt(crypto.randomInt(CHARSET.length)))
.join('')}-0`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment