From: Lady Date: Sun, 4 Sep 2022 21:19:38 +0000 (-0700) Subject: Add toString to string.js X-Git-Tag: 0.1.3~1 X-Git-Url: https://git.ladys.computer/Pisces/commitdiff_plain/20911ecea4d7c09ac104d4e059975444bb4238d7?ds=sidebyside Add toString to string.js Also properly casts some arguments of string functions to strings. --- diff --git a/string.js b/string.js index fb41e62..100f0bd 100644 --- 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 = ($) => `${$}`; diff --git a/string.test.js b/string.test.js index f70faf6..0af3e32 100644 --- a/string.test.js +++ b/string.test.js @@ -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())); + }); +});