]> Lady’s Gitweb - Pisces/commitdiff
Add toString to string.js
authorLady <redacted>
Sun, 4 Sep 2022 21:19:38 +0000 (14:19 -0700)
committerLady <redacted>
Fri, 12 May 2023 03:56:47 +0000 (20:56 -0700)
Also properly casts some arguments of string functions to strings.

string.js
string.test.js

index fb41e62724d7ed695f138d6d3e710916da67d657..100f0bd13bfb0252d1ca846925e9c900cb03b02c 100644 (file)
--- a/string.js
+++ b/string.js
@@ -275,7 +275,8 @@ export const {
    * An iterator object for iterating over code values (either code
    * units or codepoints) in a string.
    *
-   * ※ This constructor is not exposed.
+   * ※ This class is not exposed, although its methods are (through
+   * the prototypes of string code value iterator objects).
    */
   const StringCodeValueIterator = class extends identity {
     #allowSurrogates;
@@ -380,21 +381,21 @@ export const {
 
   return {
     codeUnits: ($) =>
-      new StringCodeValueIterator(call(arrayIterator, $, [])),
+      new StringCodeValueIterator(call(arrayIterator, `${$}`, [])),
     codepoints: ($) =>
       new StringCodeValueIterator(
-        call(stringIterator, $, []),
+        call(stringIterator, `${$}`, []),
         true,
       ),
     scalarValues: ($) =>
       new StringCodeValueIterator(
-        call(stringIterator, $, []),
+        call(stringIterator, `${$}`, []),
         false,
       ),
     scalarValueString: ($) =>
       stringFromCodepoints(...objectCreate(
         scalarValueIterablePrototype,
-        { source: { value: $ } },
+        { source: { value: `${$}` } },
       )),
   };
 })();
@@ -659,3 +660,11 @@ export const stripLeadingAndTrailingASCIIWhitespace = (() => {
  * value according to the algorithm of String::substring.
  */
 export const substring = makeCallable(String.prototype.substring);
+
+/**
+ * Returns the result of converting the provided value to a string.
+ *
+ * ☡ This method throws for symbols and other objects without a string
+ * representation.
+ */
+export const toString = ($) => `${$}`;
index f70faf6be0b569a7e23ab22c483a6c34f7a44400..0af3e323f0c252f79f8bcfa64c59b5379352fb13 100644 (file)
@@ -29,6 +29,7 @@ import {
   splitOnCommas,
   stripAndCollapseASCIIWhitespace,
   stripLeadingAndTrailingASCIIWhitespace,
+  toString,
 } from "./string.js";
 
 describe("Matcher", () => {
@@ -529,3 +530,20 @@ describe("stripLeadingAndTrailingASCIIWhitespace", () => {
     );
   });
 });
+
+describe("toString", () => {
+  it("[[Call]] converts to a string", () => {
+    assertStrictEquals(
+      toString({
+        toString() {
+          return "success";
+        },
+      }),
+      "success",
+    );
+  });
+
+  it("[[Call]] throws when provided a symbol", () => {
+    assertThrows(() => toString(Symbol()));
+  });
+});
This page took 0.026056 seconds and 4 git commands to generate.