Skip to content

Commit

Permalink
Remove regex in favor of ascii code
Browse files Browse the repository at this point in the history
  • Loading branch information
SeanReece committed Sep 17, 2024
1 parent 00b5f7e commit bddabbf
Showing 1 changed file with 17 additions and 6 deletions.
23 changes: 17 additions & 6 deletions src/objectid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,6 @@ import { type InspectFn, defaultInspect } from './parser/utils';
import { ByteUtils } from './utils/byte_utils';
import { NumberUtils } from './utils/number_utils';

// Regular expression that checks for hex value
const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');

// Unique sequence for the current process (initialized on first use)
let PROCESS_UNIQUE: Uint8Array | null = null;

Expand Down Expand Up @@ -147,9 +144,23 @@ export class ObjectId extends BSONValue {
* @internal
* Validates the input string is a valid hex representation of an ObjectId.
*/
private static validateHexString(input: string): boolean {
if (input == null || input.length !== 24) return false;
return checkForHexRegExp.test(input);
private static validateHexString(string: string): boolean {
if (string?.length !== 24) return false;
for (let i = 0; i < 24; i++) {
const char = string.charCodeAt(i);
if (
// Check for ASCII 0-9
(char >= 48 && char <= 57) ||
// Check for ASCII a-f
(char >= 97 && char <= 102) ||
// Check for ASCII A-F
(char >= 65 && char <= 70)
) {
continue;
}
return false;
}
return true;
}

/** Returns the ObjectId id as a 24 lowercase character hex string representation */
Expand Down

0 comments on commit bddabbf

Please sign in to comment.