ScratchAddons icon indicating copy to clipboard operation
ScratchAddons copied to clipboard

Optimize `shouldCaptureComment`

Open DNin01 opened this issue 1 year ago • 1 comments

Changes

Revised the algorithm (shouldCaptureComment()) that determines whether a user is trying to say "Scratch Addons". It's now simpler and more efficient.

Old implementation New implementation
(value) => {
  // Trim whitespace:
  const trimmedValue = value
    .replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
  const limitedValue = removeReiteratedChars(
    // a..z only (remove other characters):
    trimmedValue.toLowerCase().replace(/[^a-z]+/g, "")
  );
  const regex = /scratchadons/;
  return regex.test(limitedValue);
}
(value) => {
  const limitedValue = removeReiteratedChars(
    value
      .toLowerCase()
      // a..z only (combine matches):
      .match(/[a-z]+/g)
      .join("")
  );
  return limitedValue.includes("scratchadon");
}
  • Unnecessary whitespace trimming
  • Detects "Scratch Addons"
  • Whitespace is ignored
  • Detects "Scratch Addons" and "Scratch Addon"

Tests

I did not test the code on Scratch (I don't want to post something by accident), but I still made sure the updated code works correctly.

DNin01 avatar Nov 05 '24 03:11 DNin01

From my testing, the changed implementation seems to be over twice as fast, which is nice, although negligible since comments are limited to 500 characters in length and even those take less than a tenth of a millisecond for this code to check.

Test procedure

const value = "Lorem ipsum dolor sit amet consectetur adipisicing elit. Nisi laudantium neque, fugit, velit in natus, quod dignissimos beatae sequi facere iste eligendi distinctio. Quidem excepturi aliquid reiciendis. Iusto et soluta optio, repudiandae dolore qui enim officia minima laboriosam dolorem sequi fuga? Dignissimos eius illum aliquam, eveniet commodi vitae mollitia vel iure laboriosam quae, nam incidunt, nemo culpa. Consequatur dolor dignissimos quidem, eveniet in, tempora ipsam, aspernatur nihil numquam quasi voluptatem? Ab reprehenderit perspiciatis temporibus amet placeat corporis, maiores doloremque at quam, perferendis repellendus. Neque accusamus consequatur ad natus at totam?"
console.time("match");
value.toLowerCase().match(/[a-z]+/g).join("");
console.timeEnd("match");

console.time("replace");
value.toLowerCase().replace(/[^a-z]+/g, "");
console.timeEnd("replace");
const limitedValue = value.toLowerCase().match(/[a-z]+/g).join("");

console.time("regex");
/voluptatem/.test(limitedValue);
console.timeEnd("regex");

console.time("includes");
limitedValue.includes("voluptatem");
console.timeEnd("includes");

DNin01 avatar Nov 05 '24 03:11 DNin01