From 722d61a8a282ab9f2097f9d0abaedebf5f4c5d41 Mon Sep 17 00:00:00 2001 From: Edoardo Ranghieri Date: Mon, 20 Feb 2023 23:11:59 +0100 Subject: [PATCH] perf: faster string functions instead of regexes --- src/index.ts | 19 ++++++++++++++----- tsconfig.json | 2 +- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/index.ts b/src/index.ts index 38ec57d..462f187 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,7 +25,7 @@ export function UUIDtoULID(uuid: string, opts?: NullOnInvalidInput | ThrowOnInva throw new Error("UUID to ULID conversion failed: invalid UUID input"); } - const ulid = crockfordEncode(Buffer.from(uuid.replace(/-/g, ""), "hex")); + const ulid = crockfordEncode(Buffer.from(uuid.replaceAll("-", ""), "hex")); return ulid; } @@ -46,10 +46,19 @@ export function ULIDtoUUID(ulid: string, opts?: NullOnInvalidInput | ThrowOnInva throw new Error("ULID to UUID conversion failed: invalid ULID input"); } - const uuid = crockfordDecode(ulid) - .toString("hex") - .replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, "$1-$2-$3-$4-$5") // add hyphens - .toLowerCase(); + let uuid = crockfordDecode(ulid).toString("hex"); + + // add hyphens + uuid = + uuid.substring(0, 8) + + "-" + + uuid.substring(8, 12) + + "-" + + uuid.substring(12, 16) + + "-" + + uuid.substring(16, 20) + + "-" + + uuid.substring(20); return uuid; } diff --git a/tsconfig.json b/tsconfig.json index e10029d..ffa3bcf 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "target": "ESNext", "module": "CommonJS", - "lib": [], + "lib": ["ES2021.String"], "skipLibCheck": true, "sourceMap": true, "outDir": "./dist",