Skip to content

Commit

Permalink
Add fast-bail path for string comparison (#405)
Browse files Browse the repository at this point in the history
  • Loading branch information
bartveneman authored Jul 4, 2024
1 parent 92ce554 commit d55d859
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/string-utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down Expand Up @@ -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

Expand Down
2 changes: 2 additions & 0 deletions src/string-utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'))
Expand All @@ -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', ''))
Expand Down

0 comments on commit d55d859

Please # to comment.