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";
13 getOwnPropertyDescriptors
,
21 * A RegExp·like object which only matches entire strings, and may
22 * have additional constraints specified.
24 * Matchers are callable objects and will return true if they are
25 * called with a string that they match, and false otherwise.
26 * Matchers will always return false if called with nonstrings,
27 * although other methods like `exec` coerce their arguments and may
33 const { prototype: rePrototype
} = RE
;
34 const { exec
: reExec
, toString
: reToString
} = rePrototype
;
36 Object
.getOwnPropertyDescriptor(rePrototype
, "dotAll").get;
38 Object
.getOwnPropertyDescriptor(rePrototype
, "global").get;
40 Object
.getOwnPropertyDescriptor(rePrototype
, "hasIndices").get;
42 Object
.getOwnPropertyDescriptor(rePrototype
, "ignoreCase").get;
44 Object
.getOwnPropertyDescriptor(rePrototype
, "multiline").get;
46 Object
.getOwnPropertyDescriptor(rePrototype
, "source").get;
48 Object
.getOwnPropertyDescriptor(rePrototype
, "sticky").get;
50 Object
.getOwnPropertyDescriptor(rePrototype
, "unicode").get;
52 const Matcher
= class extends identity
{
57 * Constructs a new Matcher from the provided source.
59 * If the provided source is a regular expression, then it must
60 * have the unicode flag set. Otherwise, it is interpreted as the
61 * string source of a regular expression with the unicode flag set.
63 * Other flags are taken from the provided regular expression
64 * object, if any are present.
66 * A name for the matcher may be provided as the second argument.
68 * A callable constraint on acceptable inputs may be provided as a
69 * third argument. If provided, it will be called with three
70 * arguments whenever a match appears successful: first, the string
71 * being matched, second, the match result, and third, the Matcher
72 * object itself. If the return value of this call is falsey, then
73 * the match will be considered a failure.
75 * ☡ If the provided source regular expression uses nongreedy
76 * quantifiers, it may not match the whole string even if a match
77 * with the whole string is possible. Surround the regular
78 * expression with `^(?:` and `)$` if you don’t want nongreedy
79 * regular expressions to fail when shorter matches are possible.
81 constructor(source
, name
= undefined, constraint
= null) {
84 if (typeof $ !== "string") {
85 // The provided value is not a string.
88 // The provided value is a string. Set the `lastIndex` of
89 // the regular expression to 0 and see if the first attempt
90 // at a match matches the whole string and passes the
91 // provided constraint (if present).
93 const result
= call(reExec
, regExp
, [$]);
94 return result
?.[0] === $ &&
95 (constraint
=== null || constraint($, result
, this));
99 const regExp
= this.#regExp
= (() => {
101 call(reExec
, source
, [""]); // throws if source not a RegExp
103 return new RE(`${source}`, "u");
105 const unicode
= call(getUnicode
, source
, []);
107 // The provided regular expression does not have a unicode
110 `Piscēs: Cannot create Matcher from non‐Unicode RegExp: ${source}`,
113 // The provided regular expression has a unicode flag.
114 return new RE(source
);
117 if (constraint
!== null && typeof constraint
!== "function") {
119 "Piscēs: Cannot construct Matcher: Constraint is not callable.",
122 this.#constraint
= constraint
;
123 return defineOwnProperties(
124 setPrototype(this, matcherPrototype
),
135 : `Matcher(${call(reToString, regExp, [])})`,
142 /** Gets whether the dotAll flag is present on this Matcher. */
144 return call(getDotAll
, this.#regExp
, []);
148 * Executes this Matcher on the provided value and returns the
149 * result if there is a match, or null otherwise.
151 * Matchers only match if they can match the entire value on the
154 * ☡ The match result returned by this method will be the same as
155 * that passed to the constraint function—and may have been
156 * modified by said function prior to being returned.
159 const regExp
= this.#regExp
;
160 const constraint
= this.#constraint
;
161 const string
= `${$}`;
162 regExp
.lastIndex
= 0;
163 const result
= call(reExec
, regExp
, [string
]);
165 result
?.[0] === string
&&
166 (constraint
=== null || constraint(string
, result
, this))
168 // The entire string was matched and the constraint, if
169 // present, returned a truthy value.
172 // The entire string was not matched or the constraint returned
178 /** Gets whether the global flag is present on this Matcher. */
180 return call(getGlobal
, this.#regExp
, []);
183 /** Gets whether the hasIndices flag is present on this Matcher. */
185 return call(getHasIndices
, this.#regExp
, []);
188 /** Gets whether the ignoreCase flag is present on this Matcher. */
190 return call(getIgnoreCase
, this.#regExp
, []);
193 /** Gets whether the multiline flag is present on this Matcher. */
195 return call(getMultiline
, this.#regExp
, []);
198 /** Gets the regular expression source for this Matcher. */
200 return call(getSource
, this.#regExp
, []);
203 /** Gets whether the sticky flag is present on this Matcher. */
205 return call(getSticky
, this.#regExp
, []);
209 * Gets whether the unicode flag is present on this Matcher.
211 * ※ This will always be true.
214 return call(getUnicode
, this.#regExp
, []);
218 const matcherConstructor
= defineOwnProperties(
219 class extends RegExp
{
220 constructor(...args
) {
221 return new Matcher(...args
);
225 name
: { value
: "Matcher" },
226 length
: { value
: 1 },
229 const matcherPrototype
= defineOwnProperties(
230 matcherConstructor
.prototype,
231 getOwnPropertyDescriptors(Matcher
.prototype),
232 { constructor: { value
: matcherConstructor
} },
235 return { Matcher
: matcherConstructor
};
240 * Returns the result of converting the provided value to A·S·C·I·I
246 * Returns the result of converting the provided value to A·S·C·I·I
252 toLowerCase
: stringToLowercase
,
253 toUpperCase
: stringToUppercase
,
254 } = String
.prototype;
256 asciiLowercase
: ($) =>
260 makeCallable(stringToLowercase
),
262 asciiUppercase
: ($) =>
266 makeCallable(stringToUppercase
),
273 * Returns an iterator over the code units in the string
274 * representation of the provided value.
279 * Returns an iterator over the codepoints in the string
280 * representation of the provided value.
285 * Returns an iterator over the scalar values in the string
286 * representation of the provided value.
288 * Codepoints which are not valid Unicode scalar values are replaced
294 * Returns the result of converting the provided value to a string of
295 * scalar values by replacing (unpaired) surrogate values with
301 iterator
: iteratorSymbol
,
302 toStringTag
: toStringTagSymbol
,
304 const { [iteratorSymbol
]: arrayIterator
} = Array
.prototype;
305 const arrayIteratorPrototype
= Object
.getPrototypeOf(
306 [][iteratorSymbol
](),
308 const { next
: arrayIteratorNext
} = arrayIteratorPrototype
;
309 const iteratorPrototype
= Object
.getPrototypeOf(
310 arrayIteratorPrototype
,
312 const { [iteratorSymbol
]: stringIterator
} = String
.prototype;
313 const stringIteratorPrototype
= Object
.getPrototypeOf(
314 ""[iteratorSymbol
](),
316 const { next
: stringIteratorNext
} = stringIteratorPrototype
;
319 * An iterator object for iterating over code values (either code
320 * units or codepoints) in a string.
322 * ※ This class is not exposed, although its methods are (through
323 * the prototypes of string code value iterator objects).
325 const StringCodeValueIterator
= class extends identity
{
330 * Constructs a new string code value iterator from the provided
333 * If the provided base iterator is an array iterator, this is a
334 * code unit iterator. If the provided iterator is a string
335 * iterator and surrogates are allowed, this is a codepoint
336 * iterator. If the provided iterator is a string iterator and
337 * surrogates are not allowed, this is a scalar value iterator.
339 constructor(baseIterator
, allowSurrogates
= true) {
340 super(objectCreate(stringCodeValueIteratorPrototype
));
341 this.#allowSurrogates
= !!allowSurrogates
;
342 this.#baseIterator
= baseIterator
;
345 /** Provides the next code value in the iterator. */
347 const baseIterator
= this.#baseIterator
;
348 switch (getPrototype(baseIterator
)) {
349 case arrayIteratorPrototype
: {
350 // The base iterator is iterating over U·C·S characters.
354 } = call(arrayIteratorNext
, baseIterator
, []);
356 ? { value
: undefined, done
: true }
357 : { value
: getCodeUnit(ucsCharacter
, 0), done
: false };
359 case stringIteratorPrototype
: {
360 // The base iterator is iterating over Unicode characters.
364 } = call(stringIteratorNext
, baseIterator
, []);
366 // The base iterator has been exhausted.
367 return { value
: undefined, done
: true };
369 // The base iterator provided a character; yield the
371 const codepoint
= getCodepoint(character
, 0);
373 value
: this.#allowSurrogates
|| codepoint
<= 0xD7FF ||
382 // Should not be possible!
384 "Piscēs: Unrecognized base iterator type in %StringCodeValueIterator%.",
392 next
: stringCodeValueIteratorNext
,
393 } = StringCodeValueIterator
.prototype;
394 const stringCodeValueIteratorPrototype
= objectCreate(
400 value
: stringCodeValueIteratorNext
,
403 [toStringTagSymbol
]: {
406 value
: "String Code Value Iterator",
411 const scalarValueIterablePrototype
= {
415 stringCodeValueIteratorNext
,
416 new StringCodeValueIterator(
417 call(stringIterator
, this.source
, []),
428 new StringCodeValueIterator(call(arrayIterator
, `${$}`, [])),
430 new StringCodeValueIterator(
431 call(stringIterator
, `${$}`, []),
435 new StringCodeValueIterator(
436 call(stringIterator
, `${$}`, []),
439 scalarValueString
: ($) =>
440 stringFromCodepoints(...objectCreate(
441 scalarValueIterablePrototype
,
442 { source
: { value
: `${$}` } },
448 * Returns an iterator over the codepoints in the string representation
449 * of the provided value according to the algorithm of
450 * String::[Symbol.iterator].
452 export const characters
= makeCallable(
453 String
.prototype[Symbol
.iterator
],
457 * Returns the character at the provided position in the string
458 * representation of the provided value according to the algorithm of
459 * String::codePointAt.
461 export const getCharacter
= ($, pos
) => {
462 const codepoint
= getCodepoint($, pos
);
463 return codepoint
== null
465 : stringFromCodepoints(codepoint
);
469 * Returns the code unit at the provided position in the string
470 * representation of the provided value according to the algorithm of
473 export const getCodeUnit
= makeCallable(String
.prototype.charCodeAt
);
476 * Returns the codepoint at the provided position in the string
477 * representation of the provided value according to the algorithm of
478 * String::codePointAt.
480 export const getCodepoint
= makeCallable(String
.prototype.codePointAt
);
483 * Returns the index of the first occurrence of the search string in
484 * the string representation of the provided value according to the
485 * algorithm of String::indexOf.
487 export const getFirstSubstringIndex
= makeCallable(
488 String
.prototype.indexOf
,
492 * Returns the index of the last occurrence of the search string in the
493 * string representation of the provided value according to the
494 * algorithm of String::lastIndexOf.
496 export const getLastSubstringIndex
= makeCallable(
497 String
.prototype.lastIndexOf
,
501 * Returns the result of joining the provided iterable.
503 * If no separator is provided, it defaults to ",".
505 * If a value is nullish, it will be stringified as the empty string.
507 export const join
= (() => {
508 const { join
: arrayJoin
} = Array
.prototype;
509 const join
= ($, separator
= ",") =>
510 call(arrayJoin
, [...$], [`${separator}`]);
516 * Returns a string created from the raw value of the tagged template
519 * ※ This is an alias for String.raw.
524 * Returns a string created from the provided code units.
526 * ※ This is an alias for String.fromCharCode.
528 fromCharCode
: stringFromCodeUnits
,
531 * Returns a string created from the provided codepoints.
533 * ※ This is an alias for String.fromCodePoint.
535 fromCodePoint
: stringFromCodepoints
,
539 * Returns the result of splitting the provided value on A·S·C·I·I
542 export const splitOnASCIIWhitespace
= ($) =>
543 stringSplit(stripAndCollapseASCIIWhitespace($), " ");
546 * Returns the result of splitting the provided value on commas,
547 * trimming A·S·C·I·I whitespace from the resulting tokens.
549 export const splitOnCommas
= ($) =>
551 stripLeadingAndTrailingASCIIWhitespace(
554 /[\n\r\t\f ]*,[\n\r\t\f ]*/gu,
562 * Returns the result of catenating the string representations of the
563 * provided values, returning a new string according to the algorithm
566 export const stringCatenate
= makeCallable(String
.prototype.concat
);
569 * Returns whether the string representation of the provided value ends
570 * with the provided search string according to the algorithm of
573 export const stringEndsWith
= makeCallable(String
.prototype.endsWith
);
576 * Returns whether the string representation of the provided value
577 * contains the provided search string according to the algorithm of
580 export const stringIncludes
= makeCallable(String
.prototype.includes
);
583 * Returns the result of matching the string representation of the
584 * provided value with the provided matcher according to the algorithm
587 export const stringMatch
= makeCallable(String
.prototype.match
);
590 * Returns the result of matching the string representation of the
591 * provided value with the provided matcher according to the algorithm
592 * of String::matchAll.
594 export const stringMatchAll
= makeCallable(String
.prototype.matchAll
);
597 * Returns the normalized form of the string representation of the
598 * provided value according to the algorithm of String::matchAll.
600 export const stringNormalize
= makeCallable(
601 String
.prototype.normalize
,
605 * Returns the result of padding the end of the string representation
606 * of the provided value padded until it is the desired length
607 * according to the algorithm of String::padEnd.
609 export const stringPadEnd
= makeCallable(String
.prototype.padEnd
);
612 * Returns the result of padding the start of the string representation
613 * of the provided value padded until it is the desired length
614 * according to the algorithm of String::padStart.
616 export const stringPadStart
= makeCallable(String
.prototype.padStart
);
619 * Returns the result of repeating the string representation of the
620 * provided value the provided number of times according to the
621 * algorithm of String::repeat.
623 export const stringRepeat
= makeCallable(String
.prototype.repeat
);
626 * Returns the result of replacing the string representation of the
627 * provided value with the provided replacement, using the provided
628 * matcher and according to the algorithm of String::replace.
630 export const stringReplace
= makeCallable(String
.prototype.replace
);
633 * Returns the result of replacing the string representation of the
634 * provided value with the provided replacement, using the provided
635 * matcher and according to the algorithm of String::replaceAll.
637 export const stringReplaceAll
= makeCallable(
638 String
.prototype.replaceAll
,
642 * Returns the result of searching the string representation of the
643 * provided value using the provided matcher and according to the
644 * algorithm of String::search.
646 export const stringSearch
= makeCallable(String
.prototype.search
);
649 * Returns a slice of the string representation of the provided value
650 * according to the algorithm of String::slice.
652 export const stringSlice
= makeCallable(String
.prototype.slice
);
655 * Returns the result of splitting of the string representation of the
656 * provided value on the provided separator according to the algorithm
659 export const stringSplit
= makeCallable(String
.prototype.split
);
662 * Returns whether the string representation of the provided value
663 * starts with the provided search string according to the algorithm of
664 * String::startsWith.
666 export const stringStartsWith
= makeCallable(
667 String
.prototype.startsWith
,
671 * Returns the `[[StringData]]` of the provided value.
673 * ☡ This function will throw if the provided object does not have a
674 * `[[StringData]]` internal slot.
676 export const stringValue
= makeCallable(String
.prototype.valueOf
);
679 * Returns the result of stripping leading and trailing A·S·C·I·I
680 * whitespace from the provided value and collapsing other A·S·C·I·I
681 * whitespace in the string representation of the provided value.
683 export const stripAndCollapseASCIIWhitespace
= ($) =>
684 stripLeadingAndTrailingASCIIWhitespace(
693 * Returns the result of stripping leading and trailing A·S·C·I·I
694 * whitespace from the string representation of the provided value.
696 export const stripLeadingAndTrailingASCIIWhitespace
= (() => {
697 const { exec
: reExec
} = RegExp
.prototype;
699 call(reExec
, /^[\n\r\t\f ]*([^]*?)[\n\r\t\f ]*$/u, [$])[1];
703 * Returns a substring of the string representation of the provided
704 * value according to the algorithm of String::substring.
706 export const substring
= makeCallable(String
.prototype.substring
);
709 * Returns the result of converting the provided value to a string.
711 * ☡ This method throws for symbols and other objects without a string
714 export const toString
= ($) => `${$}`;