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.
22 * Matchers are callable objects and will return true if they are
23 * called with a string that they match, and false otherwise.
24 * Matchers will always return false if called with nonstrings,
25 * although other methods like `exec` may still return true.
30 const { prototype: rePrototype
} = RE
;
31 const { exec
: reExec
, toString
: reToString
} = rePrototype
;
33 Object
.getOwnPropertyDescriptor(rePrototype
, "dotAll").get;
35 Object
.getOwnPropertyDescriptor(rePrototype
, "global").get;
37 Object
.getOwnPropertyDescriptor(rePrototype
, "hasIndices").get;
39 Object
.getOwnPropertyDescriptor(rePrototype
, "ignoreCase").get;
41 Object
.getOwnPropertyDescriptor(rePrototype
, "multiline").get;
43 Object
.getOwnPropertyDescriptor(rePrototype
, "source").get;
45 Object
.getOwnPropertyDescriptor(rePrototype
, "sticky").get;
47 Object
.getOwnPropertyDescriptor(rePrototype
, "unicode").get;
49 const Matcher
= class extends identity
{
53 * Constructs a new Matcher from the provided source.
55 * If the provided source is a regular expression, then it must
56 * have the unicode flag set. Otherwise, it is interpreted as the
57 * string source of a regular expression with the unicode flag set.
59 * Other flags are taken from the provided regular expression
60 * object, if any are present.
62 * A name for the matcher may be provided as the second argument.
64 * ☡ If the provided source regular expression uses nongreedy
65 * quantifiers, it may not match the whole string even if a match
66 * with the whole string is possible. Surround the regular
67 * expression with `^(?:` and `)$` if you don’t want nongreedy
68 * regular expressions to fail when shorter matches are possible.
70 constructor(source
, name
= undefined) {
73 if (typeof $ !== "string") {
74 // The provided value is not a string.
77 // The provided value is a string. Set the `lastIndex` of
78 // the regular expression to 0 and see if the first attempt
79 // at a match matches the whole string.
81 return call(reExec
, regExp
, [$])?.[0] === $;
85 const regExp
= this.#regExp
= (() => {
87 call(reExec
, source
, [""]); // throws if source not a RegExp
89 return new RE(`${source}`, "u");
91 const unicode
= call(getUnicode
, source
, []);
93 // The provided regular expression does not have a unicode
96 `Piscēs: Cannot create Matcher from non‐Unicode RegExp: ${source}`,
99 // The provided regular expression has a unicode flag.
100 return new RE(source
);
103 return defineOwnProperties(
104 setPrototype(this, matcherPrototype
),
115 : `Matcher(${call(reToString, regExp, [])})`,
121 /** Gets whether the dotAll flag is present on this Matcher. */
123 return call(getDotAll
, this.#regExp
, []);
127 * Executes this Matcher on the provided value and returns the
128 * result if there is a match, or null otherwise.
130 * Matchers only match if they can match the entire value on the
134 const regExp
= this.#regExp
;
135 const string
= `${$}`;
136 regExp
.lastIndex
= 0;
137 const result
= call(reExec
, regExp
, [string
]);
138 if (result
?.[0] === string
) {
139 // The entire string was matched.
142 // The entire string was not matched.
147 /** Gets whether the global flag is present on this Matcher. */
149 return call(getGlobal
, this.#regExp
, []);
152 /** Gets whether the hasIndices flag is present on this Matcher. */
154 return call(getHasIndices
, this.#regExp
, []);
157 /** Gets whether the ignoreCase flag is present on this Matcher. */
159 return call(getIgnoreCase
, this.#regExp
, []);
162 /** Gets whether the multiline flag is present on this Matcher. */
164 return call(getMultiline
, this.#regExp
, []);
167 /** Gets the regular expression source for this Matcher. */
169 return call(getSource
, this.#regExp
, []);
172 /** Gets whether the sticky flag is present on this Matcher. */
174 return call(getSticky
, this.#regExp
, []);
178 * Gets whether the unicode flag is present on this Matcher.
180 * ※ This will always be true.
183 return call(getUnicode
, this.#regExp
, []);
186 const matcherPrototype
= setPrototype(
196 * Returns the result of converting the provided value to A·S·C·I·I
202 * Returns the result of converting the provided value to A·S·C·I·I
208 toLowerCase
: stringToLowercase
,
209 toUpperCase
: stringToUppercase
,
210 } = String
.prototype;
212 asciiLowercase
: ($) =>
216 makeCallable(stringToLowercase
),
218 asciiUppercase
: ($) =>
222 makeCallable(stringToUppercase
),
229 * Returns an iterator over the code units in the string
230 * representation of the provided value.
235 * Returns an iterator over the codepoints in the string
236 * representation of the provided value.
241 * Returns an iterator over the scalar values in the string
242 * representation of the provided value.
244 * Codepoints which are not valid Unicode scalar values are replaced
250 * Returns the result of converting the provided value to a string of
251 * scalar values by replacing (unpaired) surrogate values with
257 iterator
: iteratorSymbol
,
258 toStringTag
: toStringTagSymbol
,
260 const { [iteratorSymbol
]: arrayIterator
} = Array
.prototype;
261 const arrayIteratorPrototype
= Object
.getPrototypeOf(
262 [][iteratorSymbol
](),
264 const { next
: arrayIteratorNext
} = arrayIteratorPrototype
;
265 const iteratorPrototype
= Object
.getPrototypeOf(
266 arrayIteratorPrototype
,
268 const { [iteratorSymbol
]: stringIterator
} = String
.prototype;
269 const stringIteratorPrototype
= Object
.getPrototypeOf(
270 ""[iteratorSymbol
](),
272 const { next
: stringIteratorNext
} = stringIteratorPrototype
;
275 * An iterator object for iterating over code values (either code
276 * units or codepoints) in a string.
278 * ※ This constructor is not exposed.
280 const StringCodeValueIterator
= class extends identity
{
285 * Constructs a new string code value iterator from the provided
288 * If the provided base iterator is an array iterator, this is a
289 * code unit iterator. If the provided iterator is a string
290 * iterator and surrogates are allowed, this is a codepoint
291 * iterator. If the provided iterator is a string iterator and
292 * surrogates are not allowed, this is a scalar value iterator.
294 constructor(baseIterator
, allowSurrogates
= true) {
295 super(objectCreate(stringCodeValueIteratorPrototype
));
296 this.#allowSurrogates
= !!allowSurrogates
;
297 this.#baseIterator
= baseIterator
;
300 /** Provides the next code value in the iterator. */
302 const baseIterator
= this.#baseIterator
;
303 switch (getPrototype(baseIterator
)) {
304 case arrayIteratorPrototype
: {
305 // The base iterator is iterating over U·C·S characters.
309 } = call(arrayIteratorNext
, baseIterator
, []);
311 ? { value
: undefined, done
: true }
312 : { value
: getCodeUnit(ucsCharacter
, 0), done
: false };
314 case stringIteratorPrototype
: {
315 // The base iterator is iterating over Unicode characters.
319 } = call(stringIteratorNext
, baseIterator
, []);
321 // The base iterator has been exhausted.
322 return { value
: undefined, done
: true };
324 // The base iterator provided a character; yield the
326 const codepoint
= getCodepoint(character
, 0);
328 value
: this.#allowSurrogates
|| codepoint
<= 0xD7FF ||
337 // Should not be possible!
339 "Piscēs: Unrecognized base iterator type in %StringCodeValueIterator%.",
347 next
: stringCodeValueIteratorNext
,
348 } = StringCodeValueIterator
.prototype;
349 const stringCodeValueIteratorPrototype
= objectCreate(
355 value
: stringCodeValueIteratorNext
,
358 [toStringTagSymbol
]: {
361 value
: "String Code Value Iterator",
366 const scalarValueIterablePrototype
= {
370 stringCodeValueIteratorNext
,
371 new StringCodeValueIterator(
372 call(stringIterator
, this.source
, []),
383 new StringCodeValueIterator(call(arrayIterator
, $, [])),
385 new StringCodeValueIterator(
386 call(stringIterator
, $, []),
390 new StringCodeValueIterator(
391 call(stringIterator
, $, []),
394 scalarValueString
: ($) =>
395 stringFromCodepoints(...objectCreate(
396 scalarValueIterablePrototype
,
397 { source
: { value
: $ } },
403 * Returns an iterator over the codepoints in the string representation
404 * of the provided value according to the algorithm of
405 * String::[Symbol.iterator].
407 export const characters
= makeCallable(
408 String
.prototype[Symbol
.iterator
],
412 * Returns the character at the provided position in the string
413 * representation of the provided value according to the algorithm of
414 * String::codePointAt.
416 export const getCharacter
= ($, pos
) => {
417 const codepoint
= getCodepoint($, pos
);
418 return codepoint
== null
420 : stringFromCodepoints(codepoint
);
424 * Returns the code unit at the provided position in the string
425 * representation of the provided value according to the algorithm of
428 export const getCodeUnit
= makeCallable(String
.prototype.charCodeAt
);
431 * Returns the codepoint at the provided position in the string
432 * representation of the provided value according to the algorithm of
433 * String::codePointAt.
435 export const getCodepoint
= makeCallable(String
.prototype.codePointAt
);
438 * Returns the index of the first occurrence of the search string in
439 * the string representation of the provided value according to the
440 * algorithm of String::indexOf.
442 export const getFirstSubstringIndex
= makeCallable(
443 String
.prototype.indexOf
,
447 * Returns the index of the last occurrence of the search string in the
448 * string representation of the provided value according to the
449 * algorithm of String::lastIndexOf.
451 export const getLastSubstringIndex
= makeCallable(
452 String
.prototype.lastIndexOf
,
456 * Returns the result of joining the provided iterable.
458 * If no separator is provided, it defaults to ",".
460 * If a value is nullish, it will be stringified as the empty string.
462 export const join
= (() => {
463 const { join
: arrayJoin
} = Array
.prototype;
464 const join
= ($, separator
= ",") =>
465 call(arrayJoin
, [...$], [`${separator}`]);
471 * Returns a string created from the raw value of the tagged template
474 * ※ This is an alias for String.raw.
479 * Returns a string created from the provided code units.
481 * ※ This is an alias for String.fromCharCode.
483 fromCharCode
: stringFromCodeUnits
,
486 * Returns a string created from the provided codepoints.
488 * ※ This is an alias for String.fromCodePoint.
490 fromCodePoint
: stringFromCodepoints
,
494 * Returns the result of splitting the provided value on A·S·C·I·I
497 export const splitOnASCIIWhitespace
= ($) =>
498 stringSplit(stripAndCollapseASCIIWhitespace($), " ");
501 * Returns the result of splitting the provided value on commas,
502 * trimming A·S·C·I·I whitespace from the resulting tokens.
504 export const splitOnCommas
= ($) =>
506 stripLeadingAndTrailingASCIIWhitespace(
509 /[\n\r\t\f ]*,[\n\r\t\f ]*/gu,
517 * Returns the result of catenating the string representations of the
518 * provided values, returning a new string according to the algorithm
521 export const stringCatenate
= makeCallable(String
.prototype.concat
);
524 * Returns whether the string representation of the provided value ends
525 * with the provided search string according to the algorithm of
528 export const stringEndsWith
= makeCallable(String
.prototype.endsWith
);
531 * Returns whether the string representation of the provided value
532 * contains the provided search string according to the algorithm of
535 export const stringIncludes
= makeCallable(String
.prototype.includes
);
538 * Returns the result of matching the string representation of the
539 * provided value with the provided matcher according to the algorithm
542 export const stringMatch
= makeCallable(String
.prototype.match
);
545 * Returns the result of matching the string representation of the
546 * provided value with the provided matcher according to the algorithm
547 * of String::matchAll.
549 export const stringMatchAll
= makeCallable(String
.prototype.matchAll
);
552 * Returns the normalized form of the string representation of the
553 * provided value according to the algorithm of String::matchAll.
555 export const stringNormalize
= makeCallable(
556 String
.prototype.normalize
,
560 * Returns the result of padding the end of the string representation
561 * of the provided value padded until it is the desired length
562 * according to the algorithm of String::padEnd.
564 export const stringPadEnd
= makeCallable(String
.prototype.padEnd
);
567 * Returns the result of padding the start of the string representation
568 * of the provided value padded until it is the desired length
569 * according to the algorithm of String::padStart.
571 export const stringPadStart
= makeCallable(String
.prototype.padStart
);
574 * Returns the result of repeating the string representation of the
575 * provided value the provided number of times according to the
576 * algorithm of String::repeat.
578 export const stringRepeat
= makeCallable(String
.prototype.repeat
);
581 * Returns the result of replacing the string representation of the
582 * provided value with the provided replacement, using the provided
583 * matcher and according to the algorithm of String::replace.
585 export const stringReplace
= makeCallable(String
.prototype.replace
);
588 * Returns the result of replacing the string representation of the
589 * provided value with the provided replacement, using the provided
590 * matcher and according to the algorithm of String::replaceAll.
592 export const stringReplaceAll
= makeCallable(
593 String
.prototype.replaceAll
,
597 * Returns the result of searching the string representation of the
598 * provided value using the provided matcher and according to the
599 * algorithm of String::search.
601 export const stringSearch
= makeCallable(String
.prototype.search
);
604 * Returns a slice of the string representation of the provided value
605 * according to the algorithm of String::slice.
607 export const stringSlice
= makeCallable(String
.prototype.slice
);
610 * Returns the result of splitting of the string representation of the
611 * provided value on the provided separator according to the algorithm
614 export const stringSplit
= makeCallable(String
.prototype.split
);
617 * Returns whether the string representation of the provided value
618 * starts with the provided search string according to the algorithm of
619 * String::startsWith.
621 export const stringStartsWith
= makeCallable(
622 String
.prototype.startsWith
,
626 * Returns the `[[StringData]]` of the provided value.
628 * ☡ This function will throw if the provided object does not have a
629 * `[[StringData]]` internal slot.
631 export const stringValue
= makeCallable(String
.prototype.valueOf
);
634 * Returns the result of stripping leading and trailing A·S·C·I·I
635 * whitespace from the provided value and collapsing other A·S·C·I·I
636 * whitespace in the string representation of the provided value.
638 export const stripAndCollapseASCIIWhitespace
= ($) =>
639 stripLeadingAndTrailingASCIIWhitespace(
648 * Returns the result of stripping leading and trailing A·S·C·I·I
649 * whitespace from the string representation of the provided value.
651 export const stripLeadingAndTrailingASCIIWhitespace
= (() => {
652 const { exec
: reExec
} = RegExp
.prototype;
654 call(reExec
, /^[\n\r\t\f ]*([^]*?)[\n\r\t\f ]*$/u, [$])[1];
658 * Returns a substring of the string representation of the provided
659 * value according to the algorithm of String::substring.
661 export const substring
= makeCallable(String
.prototype.substring
);