Skip to content

Commit

Permalink
Merge pull request #4 from kryptus36/main
Browse files Browse the repository at this point in the history
fix bug in fromString, adjust & add tests
  • Loading branch information
yubinTW committed Mar 26, 2024
2 parents a9bc4bb + 56b6244 commit 3728d15
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
3 changes: 2 additions & 1 deletion src/tsid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,8 +355,9 @@ export class TSID {
if (value.length !== TSID_CHARS_LENGTH) {
throw new Error(`Invalid TSID string: (len=${value.length} chars, but expected ${TSID_CHARS_LENGTH})`)
}

number = Array.from(value).reduce(
(acc, c, i) => acc + (BigInt(ALPHABET_VALUES[c.charCodeAt(0)]) << BigInt(60 - i * 5)),
(acc, c, i) => acc + (BigInt(ALPHABET.indexOf(c.toUpperCase())) << BigInt(5 * (TSID_CHARS_LENGTH - i - 1))),
BigInt(0)
)
break
Expand Down
23 changes: 21 additions & 2 deletions test/tsid.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,30 @@ describe('TSID Testing', () => {
})

test('TSID fromString should create a TSID with the correct number', () => {
const str = '0AWE5HZP3SKTK'
const str = '0FG9Y986E7Y6M'
const tsid = TSID.fromString(str, 'S')
expect(tsid.number).toBe(18409564052552383455n)
expect(tsid.number).toBe(558796316535421140n)
})

test('TSID generated with constructor should be equal to the one generated with fromString', () => {
const str = '0FG9Y986E7Y6M'
const tsid1 = TSID.fromString(str, 'S')
const tsid2 = new TSID(tsid1.number)
expect(tsid1.number).toEqual(tsid2.number)
expect(tsid1.toBytes()).toEqual(tsid2.toBytes())
expect(tsid1.toString()).toEqual(tsid2.toString())
});

test('Random TSID should be compatible across types', () => {
const tsid1 = getTsid()
const tsid2 = TSID.fromBytes(tsid1.toBytes())
const tsid3 = TSID.fromString(tsid1.toString(), 'S')
const tsid4 = new TSID(tsid1.number)
expect(tsid1.number).toEqual(tsid2.number)
expect(tsid1.number).toEqual(tsid3.number)
expect(tsid1.number).toEqual(tsid4.number)
});

describe('Property-based Testing', () => {
test('For any size TSID array, first item should small than the second one', () => {
fc.assert(
Expand Down

0 comments on commit 3728d15

Please sign in to comment.