From d55d859eb95fd5a624fcca76b3052cce01b4a356 Mon Sep 17 00:00:00 2001 From: Bart Veneman <1536852+bartveneman@users.noreply.github.com> Date: Thu, 4 Jul 2024 10:09:24 +0200 Subject: [PATCH] Add fast-bail path for string comparison (#405) --- src/string-utils.js | 7 +++++++ src/string-utils.test.js | 2 ++ 2 files changed, 9 insertions(+) diff --git a/src/string-utils.js b/src/string-utils.js index e72fd467..53e39f57 100644 --- a/src/string-utils.js +++ b/src/string-utils.js @@ -26,9 +26,12 @@ function compareChar(referenceCode, testCode) { * @returns {boolean} true if the two strings are the same, false otherwise */ export function strEquals(base, maybe) { + if (base === maybe) return true + let len = base.length; if (len !== maybe.length) return false + for (let i = 0; i < len; i++) { if (compareChar(base.charCodeAt(i), maybe.charCodeAt(i)) === false) { return false @@ -50,6 +53,8 @@ export function strEquals(base, maybe) { * @returns {boolean} true if `test` ends with `base`, false otherwise */ export function endsWith(base, maybe) { + if (base === maybe) return true + let len = maybe.length let offset = len - base.length @@ -79,6 +84,8 @@ export function endsWith(base, maybe) { * @returns {boolean} true if `base` starts with `maybe`, false otherwise */ export function startsWith(base, maybe) { + if (base === maybe) return true + let len = base.length if (maybe.length < len) return false diff --git a/src/string-utils.test.js b/src/string-utils.test.js index 2347bf25..73d2b74a 100644 --- a/src/string-utils.test.js +++ b/src/string-utils.test.js @@ -19,6 +19,7 @@ StringUtils('endsWith', () => { assert.ok(endsWith('keyframes', '-webkit-keyframes')) assert.ok(endsWith('keyframes', 'testkeyframes')) assert.ok(endsWith('keyframes', 'testKeyframes')) + assert.ok(endsWith('test', 'test')) assert.not.ok(endsWith('keyframes', '')) assert.not.ok(endsWith('keyframes', 'test')) @@ -30,6 +31,7 @@ StringUtils('startsWith', () => { assert.ok(startsWith('animation', 'animation')) assert.ok(startsWith('animation', 'animation-duration')) assert.ok(startsWith('animation', 'Animation')) + assert.ok(startsWith('test', 'test')) assert.not.ok(startsWith('data:', 'nope')) assert.not.ok(startsWith('test', ''))