]> Lady’s Gitweb - Pisces/commitdiff
Add support for constraints to Matcher 0.1.4
authorLady <redacted>
Thu, 8 Sep 2022 03:17:51 +0000 (20:17 -0700)
committerLady <redacted>
Fri, 12 May 2023 03:56:48 +0000 (20:56 -0700)
string.js
string.test.js

index 100f0bd13bfb0252d1ca846925e9c900cb03b02c..8c858cd66a527b56c8a0d591a75d77e1f5134b60 100644 (file)
--- a/string.js
+++ b/string.js
@@ -17,12 +17,14 @@ import {
 
 export const {
   /**
-   * A RegExp·like object which only matches entire strings.
+   * A RegExp·like object which only matches entire strings, and may
+   * have additional constraints specified.
    *
    * Matchers are callable objects and will return true if they are
    * called with a string that they match, and false otherwise.
    * Matchers will always return false if called with nonstrings,
-   * although other methods like `exec` may still return true.
+   * although other methods like `exec` coerce their arguments and may
+   * still return true.
    */
   Matcher,
 } = (() => {
@@ -47,6 +49,7 @@ export const {
     Object.getOwnPropertyDescriptor(rePrototype, "unicode").get;
 
   const Matcher = class extends identity {
+    #constraint;
     #regExp;
 
     /**
@@ -61,13 +64,20 @@ export const {
      *
      * A name for the matcher may be provided as the second argument.
      *
+     * A callable constraint on acceptable inputs may be provided as a
+     * third argument. If provided, it will be called with two
+     * arguments whenever a match appears successful: first, the string
+     * being matched, and second, the Matcher object itself. If the
+     * return value of this call is falsey, then the match will be
+     * considered a failure.
+     *
      * ☡ If the provided source regular expression uses nongreedy
      * quantifiers, it may not match the whole string even if a match
      * with the whole string is possible. Surround the regular
      * expression with `^(?:` and `)$` if you don’t want nongreedy
      * regular expressions to fail when shorter matches are possible.
      */
-    constructor(source, name = undefined) {
+    constructor(source, name = undefined, constraint = null) {
       super(
         ($) => {
           if (typeof $ !== "string") {
@@ -76,9 +86,11 @@ export const {
           } else {
             // The provided value is a string. Set the `lastIndex` of
             // the regular expression to 0 and see if the first attempt
-            // at a match matches the whole string.
+            // at a match matches the whole string and passes the
+            // provided constraint (if present).
             regExp.lastIndex = 0;
-            return call(reExec, regExp, [$])?.[0] === $;
+            return call(reExec, regExp, [$])?.[0] === $ &&
+              (constraint === null || constraint($, this));
           }
         },
       );
@@ -100,22 +112,29 @@ export const {
           return new RE(source);
         }
       })();
-      return defineOwnProperties(
-        setPrototype(this, matcherPrototype),
-        {
-          lastIndex: {
-            configurable: false,
-            enumerable: false,
-            value: 0,
-            writable: false,
-          },
-          name: {
-            value: name != null
-              ? `${name}`
-              : `Matcher(${call(reToString, regExp, [])})`,
+      if (constraint !== null && typeof constraint !== "function") {
+        throw new TypeError(
+          "Piscēs: Cannot construct Matcher: Constraint is not callable.",
+        );
+      } else {
+        this.#constraint = constraint;
+        return defineOwnProperties(
+          setPrototype(this, matcherPrototype),
+          {
+            lastIndex: {
+              configurable: false,
+              enumerable: false,
+              value: 0,
+              writable: false,
+            },
+            name: {
+              value: name != null
+                ? `${name}`
+                : `Matcher(${call(reToString, regExp, [])})`,
+            },
           },
-        },
-      );
+        );
+      }
     }
 
     /** Gets whether the dotAll flag is present on this Matcher. */
@@ -132,14 +151,20 @@ export const {
      */
     exec($) {
       const regExp = this.#regExp;
+      const constraint = this.#constraint;
       const string = `${$}`;
       regExp.lastIndex = 0;
       const result = call(reExec, regExp, [string]);
-      if (result?.[0] === string) {
-        // The entire string was matched.
+      if (
+        result?.[0] === string &&
+        (constraint === null || constraint(string, this))
+      ) {
+        // The entire string was matched and the constraint, if
+        // present, returned a truthy value.
         return result;
       } else {
-        // The entire string was not matched.
+        // The entire string was not matched or the constraint returned
+        // a falsey value.
         return null;
       }
     }
index 0af3e323f0c252f79f8bcfa64c59b5379352fb13..52e848c3b75bcde588593512b66137d20ce34c22 100644 (file)
 import {
   assert,
   assertEquals,
+  assertSpyCall,
+  assertSpyCalls,
   assertStrictEquals,
   assertThrows,
   describe,
   it,
+  spy,
 } from "./dev-deps.js";
 import {
   asciiLowercase,
@@ -60,6 +63,10 @@ describe("Matcher", () => {
     assert(new Matcher("") instanceof RegExp);
   });
 
+  it("[[Construct]] throws when provided with a noncallable, non·null third argument", () => {
+    assertThrows(() => new Matcher("", undefined, "failure"));
+  });
+
   describe("::dotAll", () => {
     it("[[Get]] returns true when the dotAll flag is present", () => {
       assertStrictEquals(new Matcher(/(?:)/su).dotAll, true);
@@ -76,10 +83,47 @@ describe("Matcher", () => {
         [...new Matcher(/.(?<wow>(?:.(?=.))*)(.)?/u).exec("success")],
         ["success", "ucces", "s"],
       );
+      assertEquals(
+        [...new Matcher(
+          /.(?<wow>(?:.(?=.))*)(.)?/u,
+          undefined,
+          ($) => $ === "success",
+        ).exec("success")],
+        ["success", "ucces", "s"],
+      );
+    });
+
+    it("[[Call]] calls the constraint if the match succeeds", () => {
+      const constraint = spy((_) => true);
+      const matcher = new Matcher(".*", undefined, constraint);
+      matcher.exec({
+        toString() {
+          return "etaoin";
+        },
+      });
+      assertSpyCalls(constraint, 1);
+      assertSpyCall(constraint, 0, {
+        args: ["etaoin", matcher],
+        self: undefined,
+      });
+    });
+
+    it("[[Call]] does not call the constraint if the match fails", () => {
+      const constraint = spy((_) => true);
+      const matcher = new Matcher("", undefined, constraint);
+      matcher.exec("failure");
+      assertSpyCalls(constraint, 0);
     });
 
     it("[[Call]] returns null given a partial match", () => {
-      assertEquals(new Matcher("").exec("failure"), null);
+      assertStrictEquals(new Matcher("").exec("failure"), null);
+    });
+
+    it("[[Call]] returns null if the constraint fails", () => {
+      assertStrictEquals(
+        new Matcher(".*", undefined, () => false).exec(""),
+        null,
+      );
     });
   });
 
@@ -150,12 +194,43 @@ describe("Matcher", () => {
     it("[[Call]] returns true for a complete match", () => {
       assertStrictEquals(new Matcher("")(""), true);
       assertStrictEquals(new Matcher(/.*/su)("success\nyay"), true);
+      assertStrictEquals(
+        new Matcher(/.*/su, undefined, ($) => $ === "success")(
+          "success",
+        ),
+        true,
+      );
+    });
+
+    it("[[Call]] calls the constraint if the match succeeds", () => {
+      const constraint = spy((_) => true);
+      const matcher = new Matcher(".*", undefined, constraint);
+      matcher("etaoin");
+      assertSpyCalls(constraint, 1);
+      assertSpyCall(constraint, 0, {
+        args: ["etaoin", matcher],
+        self: undefined,
+      });
+    });
+
+    it("[[Call]] does not call the constraint if the match fails", () => {
+      const constraint = spy((_) => true);
+      const matcher = new Matcher("", undefined, constraint);
+      matcher("failure");
+      assertSpyCalls(constraint, 0);
     });
 
     it("[[Call]] returns false for a partial match", () => {
       assertStrictEquals(new Matcher("")("failure"), false);
       assertStrictEquals(new Matcher(/.*/u)("failure\nno"), false);
     });
+
+    it("[[Call]] returns false if the constraint fails", () => {
+      assertStrictEquals(
+        new Matcher(".*", undefined, () => false)(""),
+        false,
+      );
+    });
   });
 
   describe("~lastIndex", () => {
This page took 0.354199 seconds and 4 git commands to generate.