1 // ♓🌟 Piscēs ∷ string.js
2 // ====================================================================
4 // Copyright © 2022 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";
20 * A RegExp·like object which only matches entire strings, and may
21 * have additional constraints specified.
23 * Matchers are callable objects and will return true if they are
24 * called with a string that they match, and false otherwise.
25 * Matchers will always return false if called with nonstrings,
26 * although other methods like `exec` coerce their arguments and may
32 const { prototype: rePrototype
} = RE
;
33 const { exec
: reExec
, toString
: reToString
} = rePrototype
;
35 Object
.getOwnPropertyDescriptor(rePrototype
, "dotAll").get;
37 Object
.getOwnPropertyDescriptor(rePrototype
, "global").get;
39 Object
.getOwnPropertyDescriptor(rePrototype
, "hasIndices").get;
41 Object
.getOwnPropertyDescriptor(rePrototype
, "ignoreCase").get;
43 Object
.getOwnPropertyDescriptor(rePrototype
, "multiline").get;
45 Object
.getOwnPropertyDescriptor(rePrototype
, "source").get;
47 Object
.getOwnPropertyDescriptor(rePrototype
, "sticky").get;
49 Object
.getOwnPropertyDescriptor(rePrototype
, "unicode").get;
51 const Matcher
= class extends identity
{
56 * Constructs a new Matcher from the provided source.
58 * If the provided source is a regular expression, then it must
59 * have the unicode flag set. Otherwise, it is interpreted as the
60 * string source of a regular expression with the unicode flag set.
62 * Other flags are taken from the provided regular expression
63 * object, if any are present.
65 * A name for the matcher may be provided as the second argument.
67 * A callable constraint on acceptable inputs may be provided as a
68 * third argument. If provided, it will be called with three
69 * arguments whenever a match appears successful: first, the string
70 * being matched, second, the match result, and third, the Matcher
71 * object itself. If the return value of this call is falsey, then
72 * the match will be considered a failure.
74 * ☡ If the provided source regular expression uses nongreedy
75 * quantifiers, it may not match the whole string even if a match
76 * with the whole string is possible. Surround the regular
77 * expression with `^(?:` and `)$` if you don’t want nongreedy
78 * regular expressions to fail when shorter matches are possible.
80 constructor(source
, name
= undefined, constraint
= null) {
83 if (typeof $ !== "string") {
84 // The provided value is not a string.
87 // The provided value is a string. Set the `lastIndex` of
88 // the regular expression to 0 and see if the first attempt
89 // at a match matches the whole string and passes the
90 // provided constraint (if present).
92 const result
= call(reExec
, regExp
, [$]);
93 return result
?.[0] === $ &&
94 (constraint
=== null || constraint($, result
, this));
98 const regExp
= this.#regExp
= (() => {
100 call(reExec
, source
, [""]); // throws if source not a RegExp
102 return new RE(`${source}`, "u");
104 const unicode
= call(getUnicode
, source
, []);
106 // The provided regular expression does not have a unicode
109 `Piscēs: Cannot create Matcher from non‐Unicode RegExp: ${source}`,
112 // The provided regular expression has a unicode flag.
113 return new RE(source
);
116 if (constraint
!== null && typeof constraint
!== "function") {
118 "Piscēs: Cannot construct Matcher: Constraint is not callable.",
121 this.#constraint
= constraint
;
122 return defineOwnProperties(
123 setPrototype(this, matcherPrototype
),
134 : `Matcher(${call(reToString, regExp, [])})`,
141 /** Gets whether the dotAll flag is present on this Matcher. */
143 return call(getDotAll
, this.#regExp
, []);
147 * Executes this Matcher on the provided value and returns the
148 * result if there is a match, or null otherwise.
150 * Matchers only match if they can match the entire value on the
153 * ☡ The match result returned by this method will be the same as
154 * that passed to the constraint function—and may have been
155 * modified by said function prior to being returned.
158 const regExp
= this.#regExp
;
159 const constraint
= this.#constraint
;
160 const string
= `${$}`;
161 regExp
.lastIndex
= 0;
162 const result
= call(reExec
, regExp
, [string
]);
164 result
?.[0] === string
&&
165 (constraint
=== null || constraint(string
, result
, this))
167 // The entire string was matched and the constraint, if
168 // present, returned a truthy value.
171 // The entire string was not matched or the constraint returned
177 /** Gets whether the global flag is present on this Matcher. */
179 return call(getGlobal
, this.#regExp
, []);
182 /** Gets whether the hasIndices flag is present on this Matcher. */
184 return call(getHasIndices
, this.#regExp
, []);
187 /** Gets whether the ignoreCase flag is present on this Matcher. */
189 return call(getIgnoreCase
, this.#regExp
, []);
192 /** Gets whether the multiline flag is present on this Matcher. */
194 return call(getMultiline
, this.#regExp
, []);
197 /** Gets the regular expression source for this Matcher. */
199 return call(getSource
, this.#regExp
, []);
202 /** Gets whether the sticky flag is present on this Matcher. */
204 return call(getSticky
, this.#regExp
, []);
208 * Gets whether the unicode flag is present on this Matcher.
210 * ※ This will always be true.
213 return call(getUnicode
, this.#regExp
, []);
216 const matcherPrototype
= setPrototype(
226 * Returns the result of converting the provided value to A·S·C·I·I
232 * Returns the result of converting the provided value to A·S·C·I·I
238 toLowerCase
: stringToLowercase
,
239 toUpperCase
: stringToUppercase
,
240 } = String
.prototype;
242 asciiLowercase
: ($) =>
246 makeCallable(stringToLowercase
),
248 asciiUppercase
: ($) =>
252 makeCallable(stringToUppercase
),
259 * Returns an iterator over the code units in the string
260 * representation of the provided value.
265 * Returns an iterator over the codepoints in the string
266 * representation of the provided value.
271 * Returns an iterator over the scalar values in the string
272 * representation of the provided value.
274 * Codepoints which are not valid Unicode scalar values are replaced
280 * Returns the result of converting the provided value to a string of
281 * scalar values by replacing (unpaired) surrogate values with
287 iterator
: iteratorSymbol
,
288 toStringTag
: toStringTagSymbol
,
290 const { [iteratorSymbol
]: arrayIterator
} = Array
.prototype;
291 const arrayIteratorPrototype
= Object
.getPrototypeOf(
292 [][iteratorSymbol
](),
294 const { next
: arrayIteratorNext
} = arrayIteratorPrototype
;
295 const iteratorPrototype
= Object
.getPrototypeOf(
296 arrayIteratorPrototype
,
298 const { [iteratorSymbol
]: stringIterator
} = String
.prototype;
299 const stringIteratorPrototype
= Object
.getPrototypeOf(
300 ""[iteratorSymbol
](),
302 const { next
: stringIteratorNext
} = stringIteratorPrototype
;
305 * An iterator object for iterating over code values (either code
306 * units or codepoints) in a string.
308 * ※ This class is not exposed, although its methods are (through
309 * the prototypes of string code value iterator objects).
311 const StringCodeValueIterator
= class extends identity
{
316 * Constructs a new string code value iterator from the provided
319 * If the provided base iterator is an array iterator, this is a
320 * code unit iterator. If the provided iterator is a string
321 * iterator and surrogates are allowed, this is a codepoint
322 * iterator. If the provided iterator is a string iterator and
323 * surrogates are not allowed, this is a scalar value iterator.
325 constructor(baseIterator
, allowSurrogates
= true) {
326 super(objectCreate(stringCodeValueIteratorPrototype
));
327 this.#allowSurrogates
= !!allowSurrogates
;
328 this.#baseIterator
= baseIterator
;
331 /** Provides the next code value in the iterator. */
333 const baseIterator
= this.#baseIterator
;
334 switch (getPrototype(baseIterator
)) {
335 case arrayIteratorPrototype
: {
336 // The base iterator is iterating over U·C·S characters.
340 } = call(arrayIteratorNext
, baseIterator
, []);
342 ? { value
: undefined, done
: true }
343 : { value
: getCodeUnit(ucsCharacter
, 0), done
: false };
345 case stringIteratorPrototype
: {
346 // The base iterator is iterating over Unicode characters.
350 } = call(stringIteratorNext
, baseIterator
, []);
352 // The base iterator has been exhausted.
353 return { value
: undefined, done
: true };
355 // The base iterator provided a character; yield the
357 const codepoint
= getCodepoint(character
, 0);
359 value
: this.#allowSurrogates
|| codepoint
<= 0xD7FF ||
368 // Should not be possible!
370 "Piscēs: Unrecognized base iterator type in %StringCodeValueIterator%.",
378 next
: stringCodeValueIteratorNext
,
379 } = StringCodeValueIterator
.prototype;
380 const stringCodeValueIteratorPrototype
= objectCreate(
386 value
: stringCodeValueIteratorNext
,
389 [toStringTagSymbol
]: {
392 value
: "String Code Value Iterator",
397 const scalarValueIterablePrototype
= {
401 stringCodeValueIteratorNext
,
402 new StringCodeValueIterator(
403 call(stringIterator
, this.source
, []),
414 new StringCodeValueIterator(call(arrayIterator
, `${$}`, [])),
416 new StringCodeValueIterator(
417 call(stringIterator
, `${$}`, []),
421 new StringCodeValueIterator(
422 call(stringIterator
, `${$}`, []),
425 scalarValueString
: ($) =>
426 stringFromCodepoints(...objectCreate(
427 scalarValueIterablePrototype
,
428 { source
: { value
: `${$}` } },
434 * Returns an iterator over the codepoints in the string representation
435 * of the provided value according to the algorithm of
436 * String::[Symbol.iterator].
438 export const characters
= makeCallable(
439 String
.prototype[Symbol
.iterator
],
443 * Returns the character at the provided position in the string
444 * representation of the provided value according to the algorithm of
445 * String::codePointAt.
447 export const getCharacter
= ($, pos
) => {
448 const codepoint
= getCodepoint($, pos
);
449 return codepoint
== null
451 : stringFromCodepoints(codepoint
);
455 * Returns the code unit at the provided position in the string
456 * representation of the provided value according to the algorithm of
459 export const getCodeUnit
= makeCallable(String
.prototype.charCodeAt
);
462 * Returns the codepoint at the provided position in the string
463 * representation of the provided value according to the algorithm of
464 * String::codePointAt.
466 export const getCodepoint
= makeCallable(String
.prototype.codePointAt
);
469 * Returns the index of the first occurrence of the search string in
470 * the string representation of the provided value according to the
471 * algorithm of String::indexOf.
473 export const getFirstSubstringIndex
= makeCallable(
474 String
.prototype.indexOf
,
478 * Returns the index of the last occurrence of the search string in the
479 * string representation of the provided value according to the
480 * algorithm of String::lastIndexOf.
482 export const getLastSubstringIndex
= makeCallable(
483 String
.prototype.lastIndexOf
,
487 * Returns the result of joining the provided iterable.
489 * If no separator is provided, it defaults to ",".
491 * If a value is nullish, it will be stringified as the empty string.
493 export const join
= (() => {
494 const { join
: arrayJoin
} = Array
.prototype;
495 const join
= ($, separator
= ",") =>
496 call(arrayJoin
, [...$], [`${separator}`]);
502 * Returns a string created from the raw value of the tagged template
505 * ※ This is an alias for String.raw.
510 * Returns a string created from the provided code units.
512 * ※ This is an alias for String.fromCharCode.
514 fromCharCode
: stringFromCodeUnits
,
517 * Returns a string created from the provided codepoints.
519 * ※ This is an alias for String.fromCodePoint.
521 fromCodePoint
: stringFromCodepoints
,
525 * Returns the result of splitting the provided value on A·S·C·I·I
528 export const splitOnASCIIWhitespace
= ($) =>
529 stringSplit(stripAndCollapseASCIIWhitespace($), " ");
532 * Returns the result of splitting the provided value on commas,
533 * trimming A·S·C·I·I whitespace from the resulting tokens.
535 export const splitOnCommas
= ($) =>
537 stripLeadingAndTrailingASCIIWhitespace(
540 /[\n\r\t\f ]*,[\n\r\t\f ]*/gu,
548 * Returns the result of catenating the string representations of the
549 * provided values, returning a new string according to the algorithm
552 export const stringCatenate
= makeCallable(String
.prototype.concat
);
555 * Returns whether the string representation of the provided value ends
556 * with the provided search string according to the algorithm of
559 export const stringEndsWith
= makeCallable(String
.prototype.endsWith
);
562 * Returns whether the string representation of the provided value
563 * contains the provided search string according to the algorithm of
566 export const stringIncludes
= makeCallable(String
.prototype.includes
);
569 * Returns the result of matching the string representation of the
570 * provided value with the provided matcher according to the algorithm
573 export const stringMatch
= makeCallable(String
.prototype.match
);
576 * Returns the result of matching the string representation of the
577 * provided value with the provided matcher according to the algorithm
578 * of String::matchAll.
580 export const stringMatchAll
= makeCallable(String
.prototype.matchAll
);
583 * Returns the normalized form of the string representation of the
584 * provided value according to the algorithm of String::matchAll.
586 export const stringNormalize
= makeCallable(
587 String
.prototype.normalize
,
591 * Returns the result of padding the end of the string representation
592 * of the provided value padded until it is the desired length
593 * according to the algorithm of String::padEnd.
595 export const stringPadEnd
= makeCallable(String
.prototype.padEnd
);
598 * Returns the result of padding the start of the string representation
599 * of the provided value padded until it is the desired length
600 * according to the algorithm of String::padStart.
602 export const stringPadStart
= makeCallable(String
.prototype.padStart
);
605 * Returns the result of repeating the string representation of the
606 * provided value the provided number of times according to the
607 * algorithm of String::repeat.
609 export const stringRepeat
= makeCallable(String
.prototype.repeat
);
612 * Returns the result of replacing the string representation of the
613 * provided value with the provided replacement, using the provided
614 * matcher and according to the algorithm of String::replace.
616 export const stringReplace
= makeCallable(String
.prototype.replace
);
619 * Returns the result of replacing the string representation of the
620 * provided value with the provided replacement, using the provided
621 * matcher and according to the algorithm of String::replaceAll.
623 export const stringReplaceAll
= makeCallable(
624 String
.prototype.replaceAll
,
628 * Returns the result of searching the string representation of the
629 * provided value using the provided matcher and according to the
630 * algorithm of String::search.
632 export const stringSearch
= makeCallable(String
.prototype.search
);
635 * Returns a slice of the string representation of the provided value
636 * according to the algorithm of String::slice.
638 export const stringSlice
= makeCallable(String
.prototype.slice
);
641 * Returns the result of splitting of the string representation of the
642 * provided value on the provided separator according to the algorithm
645 export const stringSplit
= makeCallable(String
.prototype.split
);
648 * Returns whether the string representation of the provided value
649 * starts with the provided search string according to the algorithm of
650 * String::startsWith.
652 export const stringStartsWith
= makeCallable(
653 String
.prototype.startsWith
,
657 * Returns the `[[StringData]]` of the provided value.
659 * ☡ This function will throw if the provided object does not have a
660 * `[[StringData]]` internal slot.
662 export const stringValue
= makeCallable(String
.prototype.valueOf
);
665 * Returns the result of stripping leading and trailing A·S·C·I·I
666 * whitespace from the provided value and collapsing other A·S·C·I·I
667 * whitespace in the string representation of the provided value.
669 export const stripAndCollapseASCIIWhitespace
= ($) =>
670 stripLeadingAndTrailingASCIIWhitespace(
679 * Returns the result of stripping leading and trailing A·S·C·I·I
680 * whitespace from the string representation of the provided value.
682 export const stripLeadingAndTrailingASCIIWhitespace
= (() => {
683 const { exec
: reExec
} = RegExp
.prototype;
685 call(reExec
, /^[\n\r\t\f ]*([^]*?)[\n\r\t\f ]*$/u, [$])[1];
689 * Returns a substring of the string representation of the provided
690 * value according to the algorithm of String::substring.
692 export const substring
= makeCallable(String
.prototype.substring
);
695 * Returns the result of converting the provided value to a string.
697 * ☡ This method throws for symbols and other objects without a string
700 export const toString
= ($) => `${$}`;