1 // ♓🌟 Piscēs ∷ string.js
2 // ====================================================================
4 // Copyright © 2022–2023 Lady [@ Lady’s Computer].
6 // This Source Code Form is subject to the terms of the Mozilla Public
7 // License, v. 2.0. If a copy of the MPL was not distributed with this
8 // file, You can obtain one at <https://mozilla.org/MPL/2.0/>.
10 import { bind
, call
, identity
, makeCallable
} from "./function.js";
13 getOwnPropertyDescriptors
,
18 import { ITERATOR
, TO_STRING_TAG
, type
} from "./value.js";
22 * A RegExp·like object which only matches entire strings, and may
23 * have additional constraints specified.
25 * Matchers are callable objects and will return true if they are
26 * called with a string that they match, and false otherwise.
27 * Matchers will always return false if called with nonstrings,
28 * although other methods like `exec` coerce their arguments and may
34 const { prototype: rePrototype
} = RE
;
35 const { exec
: reExec
, toString
: reToString
} = rePrototype
;
37 Object
.getOwnPropertyDescriptor(rePrototype
, "dotAll").get;
39 Object
.getOwnPropertyDescriptor(rePrototype
, "flags").get;
41 Object
.getOwnPropertyDescriptor(rePrototype
, "global").get;
43 Object
.getOwnPropertyDescriptor(rePrototype
, "hasIndices").get;
45 Object
.getOwnPropertyDescriptor(rePrototype
, "ignoreCase").get;
47 Object
.getOwnPropertyDescriptor(rePrototype
, "multiline").get;
49 Object
.getOwnPropertyDescriptor(rePrototype
, "source").get;
51 Object
.getOwnPropertyDescriptor(rePrototype
, "sticky").get;
53 Object
.getOwnPropertyDescriptor(rePrototype
, "unicode").get;
55 const Matcher
= class extends identity
{
60 * Constructs a new Matcher from the provided source.
62 * If the provided source is a regular expression, then it must
63 * have the unicode flag set. Otherwise, it is interpreted as the
64 * string source of a regular expression with the unicode flag set.
66 * Other flags are taken from the provided regular expression
67 * object, if any are present.
69 * A name for the matcher may be provided as the second argument.
71 * A callable constraint on acceptable inputs may be provided as a
72 * third argument. If provided, it will be called with three
73 * arguments whenever a match appears successful: first, the string
74 * being matched, second, the match result, and third, the Matcher
75 * object itself. If the return value of this call is falsey, then
76 * the match will be considered a failure.
78 * ☡ If the provided source regular expression uses nongreedy
79 * quantifiers, it may not match the whole string even if a match
80 * with the whole string is possible. Surround the regular
81 * expression with `^(?:` and `)$` if you don’t want nongreedy
82 * regular expressions to fail when shorter matches are possible.
84 constructor(source
, name
= undefined, constraint
= null) {
87 if (typeof $ !== "string") {
88 // The provided value is not a string.
91 // The provided value is a string. Set the `lastIndex` of
92 // the regular expression to 0 and see if the first attempt
93 // at a match matches the whole string and passes the
94 // provided constraint (if present).
96 const result
= call(reExec
, regExp
, [$]);
97 return result
?.[0] === $ &&
98 (constraint
=== null || constraint($, result
, this));
102 const regExp
= this.#regExp
= (() => {
104 call(reExec
, source
, [""]); // throws if source not a RegExp
106 return new RE(`${source}`, "u");
108 const unicode
= call(getUnicode
, source
, []);
110 // The provided regular expression does not have a unicode
113 `Piscēs: Cannot create Matcher from non‐Unicode RegExp: ${source}`,
116 // The provided regular expression has a unicode flag.
117 return new RE(source
);
120 if (constraint
!== null && typeof constraint
!== "function") {
122 "Piscēs: Cannot construct Matcher: Constraint is not callable.",
125 this.#constraint
= constraint
;
126 return defineOwnProperties(
127 setPrototype(this, matcherPrototype
),
138 : `Matcher(${call(reToString, regExp, [])})`,
145 /** Gets whether the dotAll flag is present on this Matcher. */
147 return call(getDotAll
, this.#regExp
, []);
151 * Executes this Matcher on the provided value and returns the
152 * result if there is a match, or null otherwise.
154 * Matchers only match if they can match the entire value on the
157 * ☡ The match result returned by this method will be the same as
158 * that passed to the constraint function—and may have been
159 * modified by said function prior to being returned.
162 const regExp
= this.#regExp
;
163 const constraint
= this.#constraint
;
164 const string
= `${$}`;
165 regExp
.lastIndex
= 0;
166 const result
= call(reExec
, regExp
, [string
]);
168 result
?.[0] === string
&&
169 (constraint
=== null || constraint(string
, result
, this))
171 // The entire string was matched and the constraint, if
172 // present, returned a truthy value.
175 // The entire string was not matched or the constraint returned
182 * Gets the flags present on this Matcher.
184 * ※ This needs to be defined because the internal RegExp object
185 * may have flags which are not yet recognized by ♓🌟 Piscēs.
188 return call(getFlags
, this.#regExp
, []);
191 /** Gets whether the global flag is present on this Matcher. */
193 return call(getGlobal
, this.#regExp
, []);
196 /** Gets whether the hasIndices flag is present on this Matcher. */
198 return call(getHasIndices
, this.#regExp
, []);
201 /** Gets whether the ignoreCase flag is present on this Matcher. */
203 return call(getIgnoreCase
, this.#regExp
, []);
206 /** Gets whether the multiline flag is present on this Matcher. */
208 return call(getMultiline
, this.#regExp
, []);
211 /** Gets the regular expression source for this Matcher. */
213 return call(getSource
, this.#regExp
, []);
216 /** Gets whether the sticky flag is present on this Matcher. */
218 return call(getSticky
, this.#regExp
, []);
222 * Gets whether the unicode flag is present on this Matcher.
224 * ※ This will always be true.
227 return call(getUnicode
, this.#regExp
, []);
231 const matcherConstructor
= defineOwnProperties(
232 class extends RegExp
{
233 constructor(...args
) {
234 return new Matcher(...args
);
238 name
: { value
: "Matcher" },
239 length
: { value
: 1 },
242 const matcherPrototype
= defineOwnProperties(
243 matcherConstructor
.prototype,
244 getOwnPropertyDescriptors(Matcher
.prototype),
245 { constructor: { value
: matcherConstructor
} },
248 return { Matcher
: matcherConstructor
};
253 * Returns the result of converting the provided value to A·S·C·I·I
259 * Returns the result of converting the provided value to A·S·C·I·I
265 toLowerCase
: stringToLowercase
,
266 toUpperCase
: stringToUppercase
,
267 } = String
.prototype;
269 asciiLowercase
: ($) =>
273 makeCallable(stringToLowercase
),
275 asciiUppercase
: ($) =>
279 makeCallable(stringToUppercase
),
286 * Returns an iterator over the code units in the string
287 * representation of the provided value.
292 * Returns an iterator over the codepoints in the string
293 * representation of the provided value.
298 * Returns an iterator over the scalar values in the string
299 * representation of the provided value.
301 * Codepoints which are not valid Unicode scalar values are replaced
307 * Returns the result of converting the provided value to a string of
308 * scalar values by replacing (unpaired) surrogate values with
313 const { [ITERATOR
]: arrayIterator
} = Array
.prototype;
314 const arrayIteratorPrototype
= Object
.getPrototypeOf(
317 const { next
: arrayIteratorNext
} = arrayIteratorPrototype
;
318 const iteratorPrototype
= Object
.getPrototypeOf(
319 arrayIteratorPrototype
,
321 const { [ITERATOR
]: stringIterator
} = String
.prototype;
322 const stringIteratorPrototype
= Object
.getPrototypeOf(
325 const { next
: stringIteratorNext
} = stringIteratorPrototype
;
328 * An iterator object for iterating over code values (either code
329 * units or codepoints) in a string.
331 * ※ This class is not exposed, although its methods are (through
332 * the prototypes of string code value iterator objects).
334 const StringCodeValueIterator
= class extends identity
{
339 * Constructs a new string code value iterator from the provided
342 * If the provided base iterator is an array iterator, this is a
343 * code unit iterator. If the provided iterator is a string
344 * iterator and surrogates are allowed, this is a codepoint
345 * iterator. If the provided iterator is a string iterator and
346 * surrogates are not allowed, this is a scalar value iterator.
348 constructor(baseIterator
, allowSurrogates
= true) {
349 super(objectCreate(stringCodeValueIteratorPrototype
));
350 this.#allowSurrogates
= !!allowSurrogates
;
351 this.#baseIterator
= baseIterator
;
354 /** Provides the next code value in the iterator. */
356 const baseIterator
= this.#baseIterator
;
357 switch (getPrototype(baseIterator
)) {
358 case arrayIteratorPrototype
: {
359 // The base iterator is iterating over U·C·S characters.
363 } = call(arrayIteratorNext
, baseIterator
, []);
365 ? { value
: undefined, done
: true }
366 : { value
: getCodeUnit(ucsCharacter
, 0), done
: false };
368 case stringIteratorPrototype
: {
369 // The base iterator is iterating over Unicode characters.
373 } = call(stringIteratorNext
, baseIterator
, []);
375 // The base iterator has been exhausted.
376 return { value
: undefined, done
: true };
378 // The base iterator provided a character; yield the
380 const codepoint
= getCodepoint(character
, 0);
382 value
: this.#allowSurrogates
|| codepoint
<= 0xD7FF ||
391 // Should not be possible!
393 "Piscēs: Unrecognized base iterator type in %StringCodeValueIterator%.",
401 next
: stringCodeValueIteratorNext
,
402 } = StringCodeValueIterator
.prototype;
403 const stringCodeValueIteratorPrototype
= objectCreate(
409 value
: stringCodeValueIteratorNext
,
415 value
: "String Code Value Iterator",
420 const scalarValueIterablePrototype
= {
424 stringCodeValueIteratorNext
,
425 new StringCodeValueIterator(
426 call(stringIterator
, this.source
, []),
437 new StringCodeValueIterator(call(arrayIterator
, `${$}`, [])),
439 new StringCodeValueIterator(
440 call(stringIterator
, `${$}`, []),
444 new StringCodeValueIterator(
445 call(stringIterator
, `${$}`, []),
448 scalarValueString
: ($) =>
449 stringFromCodepoints(...objectCreate(
450 scalarValueIterablePrototype
,
451 { source
: { value
: `${$}` } },
457 * Returns an iterator over the codepoints in the string representation
458 * of the provided value according to the algorithm of
459 * String::[Symbol.iterator].
461 export const characters
= makeCallable(
462 String
.prototype[ITERATOR
],
466 * Returns the character at the provided position in the string
467 * representation of the provided value according to the algorithm of
468 * String::codePointAt.
470 export const getCharacter
= ($, pos
) => {
471 const codepoint
= getCodepoint($, pos
);
472 return codepoint
== null
474 : stringFromCodepoints(codepoint
);
478 * Returns the code unit at the provided position in the string
479 * representation of the provided value according to the algorithm of
482 export const getCodeUnit
= makeCallable(String
.prototype.charCodeAt
);
485 * Returns the codepoint at the provided position in the string
486 * representation of the provided value according to the algorithm of
487 * String::codePointAt.
489 export const getCodepoint
= makeCallable(String
.prototype.codePointAt
);
492 * Returns the index of the first occurrence of the search string in
493 * the string representation of the provided value according to the
494 * algorithm of String::indexOf.
496 export const getFirstSubstringIndex
= makeCallable(
497 String
.prototype.indexOf
,
501 * Returns the index of the last occurrence of the search string in the
502 * string representation of the provided value according to the
503 * algorithm of String::lastIndexOf.
505 export const getLastSubstringIndex
= makeCallable(
506 String
.prototype.lastIndexOf
,
510 * Returns the result of joining the provided iterable.
512 * If no separator is provided, it defaults to ",".
514 * If a value is nullish, it will be stringified as the empty string.
516 export const join
= (() => {
517 const { join
: arrayJoin
} = Array
.prototype;
518 const join
= ($, separator
= ",") =>
519 call(arrayJoin
, [...$], [`${separator}`]);
525 * Returns a string created from the raw value of the tagged template
528 * ※ This is an alias for String.raw.
533 * Returns a string created from the provided code units.
535 * ※ This is an alias for String.fromCharCode.
537 fromCharCode
: stringFromCodeUnits
,
540 * Returns a string created from the provided codepoints.
542 * ※ This is an alias for String.fromCodePoint.
544 fromCodePoint
: stringFromCodepoints
,
548 * Returns the result of splitting the provided value on A·S·C·I·I
551 export const splitOnASCIIWhitespace
= ($) =>
552 stringSplit(stripAndCollapseASCIIWhitespace($), " ");
555 * Returns the result of splitting the provided value on commas,
556 * trimming A·S·C·I·I whitespace from the resulting tokens.
558 export const splitOnCommas
= ($) =>
560 stripLeadingAndTrailingASCIIWhitespace(
563 /[\n\r\t\f ]*,[\n\r\t\f ]*/gu,
571 * Returns the result of catenating the string representations of the
572 * provided values, returning a new string according to the algorithm
575 export const stringCatenate
= makeCallable(String
.prototype.concat
);
578 * Returns whether the string representation of the provided value ends
579 * with the provided search string according to the algorithm of
582 export const stringEndsWith
= makeCallable(String
.prototype.endsWith
);
585 * Returns whether the string representation of the provided value
586 * contains the provided search string according to the algorithm of
589 export const stringIncludes
= makeCallable(String
.prototype.includes
);
592 * Returns the result of matching the string representation of the
593 * provided value with the provided matcher according to the algorithm
596 export const stringMatch
= makeCallable(String
.prototype.match
);
599 * Returns the result of matching the string representation of the
600 * provided value with the provided matcher according to the algorithm
601 * of String::matchAll.
603 export const stringMatchAll
= makeCallable(String
.prototype.matchAll
);
606 * Returns the normalized form of the string representation of the
607 * provided value according to the algorithm of String::matchAll.
609 export const stringNormalize
= makeCallable(
610 String
.prototype.normalize
,
614 * Returns the result of padding the end of the string representation
615 * of the provided value padded until it is the desired length
616 * according to the algorithm of String::padEnd.
618 export const stringPadEnd
= makeCallable(String
.prototype.padEnd
);
621 * Returns the result of padding the start of the string representation
622 * of the provided value padded until it is the desired length
623 * according to the algorithm of String::padStart.
625 export const stringPadStart
= makeCallable(String
.prototype.padStart
);
628 * Returns the result of repeating the string representation of the
629 * provided value the provided number of times according to the
630 * algorithm of String::repeat.
632 export const stringRepeat
= makeCallable(String
.prototype.repeat
);
635 * Returns the result of replacing the string representation of the
636 * provided value with the provided replacement, using the provided
637 * matcher and according to the algorithm of String::replace.
639 export const stringReplace
= makeCallable(String
.prototype.replace
);
642 * Returns the result of replacing the string representation of the
643 * provided value with the provided replacement, using the provided
644 * matcher and according to the algorithm of String::replaceAll.
646 export const stringReplaceAll
= makeCallable(
647 String
.prototype.replaceAll
,
651 * Returns the result of searching the string representation of the
652 * provided value using the provided matcher and according to the
653 * algorithm of String::search.
655 export const stringSearch
= makeCallable(String
.prototype.search
);
658 * Returns a slice of the string representation of the provided value
659 * according to the algorithm of String::slice.
661 export const stringSlice
= makeCallable(String
.prototype.slice
);
664 * Returns the result of splitting of the string representation of the
665 * provided value on the provided separator according to the algorithm
668 export const stringSplit
= makeCallable(String
.prototype.split
);
671 * Returns whether the string representation of the provided value
672 * starts with the provided search string according to the algorithm of
673 * String::startsWith.
675 export const stringStartsWith
= makeCallable(
676 String
.prototype.startsWith
,
680 * Returns the `[[StringData]]` of the provided value.
682 * ☡ This function will throw if the provided object does not have a
683 * `[[StringData]]` internal slot.
685 export const stringValue
= makeCallable(String
.prototype.valueOf
);
688 * Returns the result of stripping leading and trailing A·S·C·I·I
689 * whitespace from the provided value and collapsing other A·S·C·I·I
690 * whitespace in the string representation of the provided value.
692 export const stripAndCollapseASCIIWhitespace
= ($) =>
693 stripLeadingAndTrailingASCIIWhitespace(
702 * Returns the result of stripping leading and trailing A·S·C·I·I
703 * whitespace from the string representation of the provided value.
705 export const stripLeadingAndTrailingASCIIWhitespace
= (() => {
706 const { exec
: reExec
} = RegExp
.prototype;
708 call(reExec
, /^[\n\r\t\f ]*([^]*?)[\n\r\t\f ]*$/u, [$])[1];
712 * Returns a substring of the string representation of the provided
713 * value according to the algorithm of String::substring.
715 export const substring
= makeCallable(String
.prototype.substring
);
718 * Returns the result of converting the provided value to a string.
720 * ☡ This method throws for symbols and other objects without a string
723 export const toString
= ($) => `${$}`;