Created
July 6, 2021 00:38
-
-
Save 117/12c3ad2381b0a4d557a14a31dbb423d5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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