Skip to content

Commit

Permalink
perf: faster string functions instead of regexes
Browse files Browse the repository at this point in the history
  • Loading branch information
TheEdoRan committed Feb 20, 2023
1 parent 978b30d commit 722d61a
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
19 changes: 14 additions & 5 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand All @@ -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;
}
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"compilerOptions": {
"target": "ESNext",
"module": "CommonJS",
"lib": [],
"lib": ["ES2021.String"],
"skipLibCheck": true,
"sourceMap": true,
"outDir": "./dist",
Expand Down

0 comments on commit 722d61a

Please sign in to comment.