From: Lady Date: Sat, 29 May 2021 20:37:16 +0000 (-0700) Subject: Initial codes X-Git-Tag: 0.1.0~15 X-Git-Url: https://git.ladys.computer/Pisces/commitdiff_plain/8c8953d378b20e194535e22214750367961b6963?ds=inline Initial codes Most of this was taken from الرشآء. --- 8c8953d378b20e194535e22214750367961b6963 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ee6256c --- /dev/null +++ b/LICENSE @@ -0,0 +1,373 @@ +Mozilla Public License Version 2.0 +================================== + +1. Definitions +-------------- + +1.1. "Contributor" + means each individual or legal entity that creates, contributes to + the creation of, or owns Covered Software. + +1.2. "Contributor Version" + means the combination of the Contributions of others (if any) used + by a Contributor and that particular Contributor's Contribution. + +1.3. "Contribution" + means Covered Software of a particular Contributor. + +1.4. "Covered Software" + means Source Code Form to which the initial Contributor has attached + the notice in Exhibit A, the Executable Form of such Source Code + Form, and Modifications of such Source Code Form, in each case + including portions thereof. + +1.5. "Incompatible With Secondary Licenses" + means + + (a) that the initial Contributor has attached the notice described + in Exhibit B to the Covered Software; or + + (b) that the Covered Software was made available under the terms of + version 1.1 or earlier of the License, but not also under the + terms of a Secondary License. + +1.6. "Executable Form" + means any form of the work other than Source Code Form. + +1.7. "Larger Work" + means a work that combines Covered Software with other material, in + a separate file or files, that is not Covered Software. + +1.8. "License" + means this document. + +1.9. "Licensable" + means having the right to grant, to the maximum extent possible, + whether at the time of the initial grant or subsequently, any and + all of the rights conveyed by this License. + +1.10. "Modifications" + means any of the following: + + (a) any file in Source Code Form that results from an addition to, + deletion from, or modification of the contents of Covered + Software; or + + (b) any new file in Source Code Form that contains any Covered + Software. + +1.11. "Patent Claims" of a Contributor + means any patent claim(s), including without limitation, method, + process, and apparatus claims, in any patent Licensable by such + Contributor that would be infringed, but for the grant of the + License, by the making, using, selling, offering for sale, having + made, import, or transfer of either its Contributions or its + Contributor Version. + +1.12. "Secondary License" + means either the GNU General Public License, Version 2.0, the GNU + Lesser General Public License, Version 2.1, the GNU Affero General + Public License, Version 3.0, or any later versions of those + licenses. + +1.13. "Source Code Form" + means the form of the work preferred for making modifications. + +1.14. "You" (or "Your") + means an individual or a legal entity exercising rights under this + License. For legal entities, "You" includes any entity that + controls, is controlled by, or is under common control with You. For + purposes of this definition, "control" means (a) the power, direct + or indirect, to cause the direction or management of such entity, + whether by contract or otherwise, or (b) ownership of more than + fifty percent (50%) of the outstanding shares or beneficial + ownership of such entity. + +2. License Grants and Conditions +-------------------------------- + +2.1. Grants + +Each Contributor hereby grants You a world-wide, royalty-free, +non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or + as part of a Larger Work; and + +(b) under Patent Claims of such Contributor to make, use, sell, offer + for sale, have made, import, and otherwise transfer either its + Contributions or its Contributor Version. + +2.2. Effective Date + +The licenses granted in Section 2.1 with respect to any Contribution +become effective for each Contribution on the date the Contributor first +distributes such Contribution. + +2.3. Limitations on Grant Scope + +The licenses granted in this Section 2 are the only rights granted under +this License. No additional rights or licenses will be implied from the +distribution or licensing of Covered Software under this License. +Notwithstanding Section 2.1(b) above, no patent license is granted by a +Contributor: + +(a) for any code that a Contributor has removed from Covered Software; + or + +(b) for infringements caused by: (i) Your and any other third party's + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + +(c) under Patent Claims infringed by Covered Software in the absence of + its Contributions. + +This License does not grant any rights in the trademarks, service marks, +or logos of any Contributor (except as may be necessary to comply with +the notice requirements in Section 3.4). + +2.4. Subsequent Licenses + +No Contributor makes additional grants as a result of Your choice to +distribute the Covered Software under a subsequent version of this +License (see Section 10.2) or under the terms of a Secondary License (if +permitted under the terms of Section 3.3). + +2.5. Representation + +Each Contributor represents that the Contributor believes its +Contributions are its original creation(s) or it has sufficient rights +to grant the rights to its Contributions conveyed by this License. + +2.6. Fair Use + +This License is not intended to limit any rights You have under +applicable copyright doctrines of fair use, fair dealing, or other +equivalents. + +2.7. Conditions + +Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted +in Section 2.1. + +3. Responsibilities +------------------- + +3.1. Distribution of Source Form + +All distribution of Covered Software in Source Code Form, including any +Modifications that You create or to which You contribute, must be under +the terms of this License. You must inform recipients that the Source +Code Form of the Covered Software is governed by the terms of this +License, and how they can obtain a copy of this License. You may not +attempt to alter or restrict the recipients' rights in the Source Code +Form. + +3.2. Distribution of Executable Form + +If You distribute Covered Software in Executable Form then: + +(a) such Covered Software must also be made available in Source Code + Form, as described in Section 3.1, and You must inform recipients of + the Executable Form how they can obtain a copy of such Source Code + Form by reasonable means in a timely manner, at a charge no more + than the cost of distribution to the recipient; and + +(b) You may distribute such Executable Form under the terms of this + License, or sublicense it under different terms, provided that the + license for the Executable Form does not attempt to limit or alter + the recipients' rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + +You may create and distribute a Larger Work under terms of Your choice, +provided that You also comply with the requirements of this License for +the Covered Software. If the Larger Work is a combination of Covered +Software with a work governed by one or more Secondary Licenses, and the +Covered Software is not Incompatible With Secondary Licenses, this +License permits You to additionally distribute such Covered Software +under the terms of such Secondary License(s), so that the recipient of +the Larger Work may, at their option, further distribute the Covered +Software under the terms of either this License or such Secondary +License(s). + +3.4. Notices + +You may not remove or alter the substance of any license notices +(including copyright notices, patent notices, disclaimers of warranty, +or limitations of liability) contained within the Source Code Form of +the Covered Software, except that You may alter any license notices to +the extent required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + +You may choose to offer, and to charge a fee for, warranty, support, +indemnity or liability obligations to one or more recipients of Covered +Software. However, You may do so only on Your own behalf, and not on +behalf of any Contributor. You must make it absolutely clear that any +such warranty, support, indemnity, or liability obligation is offered by +You alone, and You hereby agree to indemnify every Contributor for any +liability incurred by such Contributor as a result of warranty, support, +indemnity or liability terms You offer. You may include additional +disclaimers of warranty and limitations of liability specific to any +jurisdiction. + +4. Inability to Comply Due to Statute or Regulation +--------------------------------------------------- + +If it is impossible for You to comply with any of the terms of this +License with respect to some or all of the Covered Software due to +statute, judicial order, or regulation then You must: (a) comply with +the terms of this License to the maximum extent possible; and (b) +describe the limitations and the code they affect. Such description must +be placed in a text file included with all distributions of the Covered +Software under this License. Except to the extent prohibited by statute +or regulation, such description must be sufficiently detailed for a +recipient of ordinary skill to be able to understand it. + +5. Termination +-------------- + +5.1. The rights granted under this License will terminate automatically +if You fail to comply with any of its terms. However, if You become +compliant, then the rights granted under this License from a particular +Contributor are reinstated (a) provisionally, unless and until such +Contributor explicitly and finally terminates Your grants, and (b) on an +ongoing basis, if such Contributor fails to notify You of the +non-compliance by some reasonable means prior to 60 days after You have +come back into compliance. Moreover, Your grants from a particular +Contributor are reinstated on an ongoing basis if such Contributor +notifies You of the non-compliance by some reasonable means, this is the +first time You have received notice of non-compliance with this License +from such Contributor, and You become compliant prior to 30 days after +Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent +infringement claim (excluding declaratory judgment actions, +counter-claims, and cross-claims) alleging that a Contributor Version +directly or indirectly infringes any patent, then the rights granted to +You by any and all Contributors for the Covered Software under Section +2.1 of this License shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all +end user license agreements (excluding distributors and resellers) which +have been validly granted by You or Your distributors under this License +prior to termination shall survive termination. + +************************************************************************ +* * +* 6. Disclaimer of Warranty * +* ------------------------- * +* * +* Covered Software is provided under this License on an "as is" * +* basis, without warranty of any kind, either expressed, implied, or * +* statutory, including, without limitation, warranties that the * +* Covered Software is free of defects, merchantable, fit for a * +* particular purpose or non-infringing. The entire risk as to the * +* quality and performance of the Covered Software is with You. * +* Should any Covered Software prove defective in any respect, You * +* (not any Contributor) assume the cost of any necessary servicing, * +* repair, or correction. This disclaimer of warranty constitutes an * +* essential part of this License. No use of any Covered Software is * +* authorized under this License except under this disclaimer. * +* * +************************************************************************ + +************************************************************************ +* * +* 7. Limitation of Liability * +* -------------------------- * +* * +* Under no circumstances and under no legal theory, whether tort * +* (including negligence), contract, or otherwise, shall any * +* Contributor, or anyone who distributes Covered Software as * +* permitted above, be liable to You for any direct, indirect, * +* special, incidental, or consequential damages of any character * +* including, without limitation, damages for lost profits, loss of * +* goodwill, work stoppage, computer failure or malfunction, or any * +* and all other commercial damages or losses, even if such party * +* shall have been informed of the possibility of such damages. This * +* limitation of liability shall not apply to liability for death or * +* personal injury resulting from such party's negligence to the * +* extent applicable law prohibits such limitation. Some * +* jurisdictions do not allow the exclusion or limitation of * +* incidental or consequential damages, so this exclusion and * +* limitation may not apply to You. * +* * +************************************************************************ + +8. Litigation +------------- + +Any litigation relating to this License may be brought only in the +courts of a jurisdiction where the defendant maintains its principal +place of business and such litigation shall be governed by laws of that +jurisdiction, without reference to its conflict-of-law provisions. +Nothing in this Section shall prevent a party's ability to bring +cross-claims or counter-claims. + +9. Miscellaneous +---------------- + +This License represents the complete agreement concerning the subject +matter hereof. If any provision of this License is held to be +unenforceable, such provision shall be reformed only to the extent +necessary to make it enforceable. Any law or regulation which provides +that the language of a contract shall be construed against the drafter +shall not be used to construe this License against a Contributor. + +10. Versions of the License +--------------------------- + +10.1. New Versions + +Mozilla Foundation is the license steward. Except as provided in Section +10.3, no one other than the license steward has the right to modify or +publish new versions of this License. Each version will be given a +distinguishing version number. + +10.2. Effect of New Versions + +You may distribute the Covered Software under the terms of the version +of the License under which You originally received the Covered Software, +or under the terms of any subsequent version published by the license +steward. + +10.3. Modified Versions + +If you create software not governed by this License, and you want to +create a new license for such software, you may create and use a +modified version of this License if you rename the license and remove +any references to the name of the license steward (except to note that +such modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary +Licenses + +If You choose to distribute Source Code Form that is Incompatible With +Secondary Licenses under the terms of this version of the License, the +notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice +------------------------------------------- + + This Source Code Form is subject to the terms of the Mozilla Public + License, v. 2.0. If a copy of the MPL was not distributed with this + file, You can obtain one at https://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular +file, then You may include the notice in a location (such as a LICENSE +file in a relevant directory) where a recipient would be likely to look +for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - "Incompatible With Secondary Licenses" Notice +--------------------------------------------------------- + + This Source Code Form is "Incompatible With Secondary Licenses", as + defined by the Mozilla Public License, v. 2.0. diff --git a/README.markdown b/README.markdown new file mode 100644 index 0000000..93caa73 --- /dev/null +++ b/README.markdown @@ -0,0 +1,37 @@ +# ♓🧩 Piscēs + +Ecmascript building blocks. + +♓🧩 Piscēs is a Javascript (handcoded Ecmascript) library +providing various building blocks for developing complex, +precisely‐defined Javascript libraries. It provides implementations of +fundamental Ecmascript Specification functions for use in Javascript +code, plus other helpful prototypes and utilities. + +This library is **targeted at “low‐level” Javascript development**, i·e +the kind of development undertaken with the Ecmascript specification +open as reference. Taking full advantage of it requires familiarity +with things like `Reflect` and a willingness to access properties and +methods from one prototype on an unrelated object. + +**♓🧩 Piscēs was written to serve the interests of +[♓🌟 الرشآء](https://git.ladys.computer/Alrescha) development, and not +as a general‐use library.** This means that it is not extensively +documented beyond its source code, it is not rigidly versioned, and it +offers no guarantees regarding stability between versions. However, it +is written in a generic manner, such that if you find it useful, you +_can_ integrate it into your project—using ordinary Ecmascript imports +from `https://git.ladys.computer/Pisces/blob_plain/❲HASH❳:/mod.js`. +Always use a specific hash, and not a branch name like `current`, when +importing ♓🧩 Piscēs into your project. + +Piscēs is broken up into multiple files, which is perfectly acceptable +for use with [Deno](https://deno.land), but generally not considered +ideal for usage on the web. You can use the `deno bundle` command to +stitch the various source files together into a single script. + +## License + +Source files are licensed under the terms of the Mozilla Public +License, version 2.0. For more information, see +[LICENSE](./LICENSE). diff --git a/base64.js b/base64.js new file mode 100644 index 0000000..707e8e6 --- /dev/null +++ b/base64.js @@ -0,0 +1,156 @@ +// ♓🌟 Piscēs ∷ base64.js +// ==================================================================== +// +// Copyright © 2020–2022 Lady [@ Lady’s Computer]. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +/** + * Returns an ArrayBuffer generated from the provided Base64. + * + * This function can also be used as a tag for a template literal. The + * literal will be interpreted akin to `String.raw`. + */ +export const a2b = ($, ...$s) => { + const source = ( + typeof $ == "string" + ? $ + : Object.hasOwn($, "raw") + ? String.raw($, ...$s) + : `${$}` + ).replace(/[\t\n\f\r ]+/gu, ""); + const u6s = Array.prototype.map.call( + source.length % 4 == 0 ? source.replace(/={1,2}$/u, "") : source, + (character) => { + const code = character.charCodeAt(0); + const result = code >= 0x41 && code <= 0x5A + ? code - 65 + : code >= 0x61 && code <= 0x7A + ? code - 71 + : code >= 0x30 && code <= 0x39 + ? code + 4 + : code == 0x2B + ? 62 + : code == 0x2F + ? 63 + : -1; + if (result < 0) { + throw new RangeError( + `Piscēs: Invalid character in Base64: ${character}.`, + ); + } else { + return result; + } + }, + ); + const { length } = u6s; + const dataView = new DataView( + new ArrayBuffer(Math.floor(length * 3 / 4)), + ); + for (let index = 0; index < length - 1;) { + const dataIndex = Math.ceil(index * 3 / 4); + const remainder = index % 3; + if (remainder == 0) { + dataView.setUint8( + dataIndex, + (u6s[index] << 2) + (u6s[++index] >> 4), + ); + } else if (remainder == 1) { + dataView.setUint8( + dataIndex, + ((u6s[index] & 0xF) << 4) + (u6s[++index] >> 2), + ); + } else { + dataView.setUint8( + dataIndex, + ((u6s[index] & 0x3) << 6) + u6s[++index], + ); + } + } + return dataView.buffer; +}; + +/** + * Returns a (big‐endian) base64 string created from a typed array, + * buffer, or string. + * + * This function can also be used as a tag for a template literal. The + * literal will be interpreted akin to `String.raw`. + */ +export const b2a = ($, ...$s) => { + const buffer = $ instanceof ArrayBuffer + ? $ + : $ instanceof DataView || + $ instanceof Object.getPrototypeOf(Uint8Array) + ? $.buffer + : ((string) => + Array.prototype.reduce.call( + string, + (result, code·point, index) => ( + result.setUint16(index * 2, code·point.charCodeAt(0)), result + ), + new DataView(new ArrayBuffer(string.length * 2)), + ).buffer)( + typeof $ == "string" + ? $ + : Object.hasOwn($, "raw") + ? String.raw($, ...$s) + : `${$}`, + ); + const dataView = new DataView(buffer); + const { byteLength } = buffer; + const minimumLengthOfResults = Math.ceil(byteLength * 4 / 3); + const resultingCode·points = new Array( + minimumLengthOfResults + (4 - (minimumLengthOfResults % 4)) % 4, + ).fill(0x3D); + for (let index = 0; index < byteLength;) { + const code·pointIndex = Math.ceil(index * 4 / 3); + const currentIndex = code·pointIndex + +( + index % 3 == 0 && resultingCode·points[code·pointIndex] != 0x3D + ); + const remainder = currentIndex % 4; + const u6 = remainder == 0 + ? dataView.getUint8(index) >> 2 + : remainder == 1 + ? ((dataView.getUint8(index++) & 0x3) << 4) + + (index < byteLength ? dataView.getUint8(index) >> 4 : 0) + : remainder == 2 + ? ((dataView.getUint8(index++) & 0xF) << 2) + + (index < byteLength ? dataView.getUint8(index) >> 6 : 0) + : dataView.getUint8(index++) & 0x3F; + const result = u6 < 26 + ? u6 + 65 + : u6 < 52 + ? u6 + 71 + : u6 < 62 + ? u6 - 4 + : u6 < 63 + ? 43 + : u6 < 64 + ? 47 + : -1; + if (result < 0) { + throw new RangeError(`Piscēs: Unexpected Base64 value: ${u6}.`); + } else { + resultingCode·points[currentIndex] = result; + } + } + return String.fromCodePoint(...resultingCode·points); +}; + +/** + * Returns whether the provided value is a Base64 string. + * + * Returns false if the provided value is not a string primitive. + */ +export const isBase64 = ($) => { + if (typeof $ != "string") return false; + const source = $.replace(/[\t\n\f\r ]+/gu, ""); + const trimmed = source.length % 4 == 0 + ? source.replace(/={1,2}$/u, "") + : source; + return trimmed.length % 4 != 1 && + !/[^0-9A-Za-z+\/]/u.test(trimmed); +}; diff --git a/base64.test.js b/base64.test.js new file mode 100755 index 0000000..e6361a4 --- /dev/null +++ b/base64.test.js @@ -0,0 +1,105 @@ +// ♓🌟 Piscēs ∷ base64.test.js +// ==================================================================== +// +// Copyright © 2020–2022 Lady [@ Lady’s Computer]. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +import { a2b, b2a, isBase64 } from "./base64.js"; +import { + assert, + assertEquals, + assertStrictEquals, + assertThrows, +} from "./dev-deps.js"; + +const base64s = { + "AGIAYQBzAGUANgA0": "base64", + "R/Q=": new Uint16Array([62535]), + "S0lCSQ==": new Uint8ClampedArray([75, 73, 66, 73]).buffer, + YmFzZTY0: new DataView( + new Uint8Array([98, 97, 115, 101, 54, 52]).buffer, + ), +}; + +Deno.test({ + name: "Calling b2a returns the correct string.", + fn: () => + Object.entries(base64s).forEach(([key, value]) => + assertStrictEquals(b2a(value), key) + ), +}); + +Deno.test({ + name: "Calling a2b returns the correct data.", + fn: () => { + assertEquals( + a2b("AGIAYQBzAGUANgA0"), + new Uint8Array( + Array.prototype.map.call( + "\u{0}b\u{0}a\u{0}s\u{0}e\u{0}6\u{0}4", + ($) => $.charCodeAt(0), + ), + ).buffer, + ); + assertEquals( + a2b("R/Q="), + new Uint16Array([62535]).buffer, + ); + assertEquals( + a2b("S0lCSQ=="), + new Uint8ClampedArray([75, 73, 66, 73]).buffer, + ); + assertEquals( + a2b("YmFzZTY0"), + new Uint8Array([98, 97, 115, 101, 54, 52]).buffer, + ); + }, +}); + +Deno.test({ + name: "Calling a2b throws when provided with an invalid character.", + fn: () => assertThrows(() => a2b("abc_")), +}); + +Deno.test({ + name: "Calling a2b throws when provided with an invalid equals.", + fn: () => assertThrows(() => a2b("abc==")), +}); + +Deno.test({ + name: + "Calling a2b throws when provided with a length with a remainder of 1 when divided by 4.", + fn: () => { + assertThrows(() => a2b("abcde")); + assertThrows(() => a2b("abcde===")); + }, +}); + +Deno.test({ + name: "isBase64 returns true for base64 strings.", + fn: () => + Object.keys(base64s).forEach((key) => assert(isBase64(key))), +}); + +Deno.test({ + name: "isBase64 returns false for others.", + fn: () => + [ + undefined, + null, + true, + Symbol(), + 27, + 98n, + {}, + [], + () => {}, + new Proxy({}, {}), + "abc_", + "a", + "abc==", + ].forEach((value) => assert(!isBase64(value))), +}); diff --git a/collection.js b/collection.js new file mode 100644 index 0000000..6920661 --- /dev/null +++ b/collection.js @@ -0,0 +1,140 @@ +// ♓🌟 Piscēs ∷ collection.js +// ==================================================================== +// +// Copyright © 2020–2022 Lady [@ Lady’s Computer]. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +import { MAX_SAFE_INTEGER } from "./numeric.js"; +import { isObject } from "./object.js"; + +/** + * Returns -0 if the provided argument is "-0"; returns a number + * representing the index if the provided argument is a canonical + * numeric index string; otherwise, returns undefined. + * + * There is no clamping of the numeric index, but note that numbers + * above 2^53 − 1 are not safe nor valid integer indices. + */ +export const canonicalNumericIndexString = ($) => { + if (typeof $ != "string") { + return undefined; + } else if ($ === "-0") { + return -0; + } else { + const n = +$; + return $ === `${n}` ? n : undefined; + } +}; + +/** Returns whether the provided value is an array index. */ +export const isArrayIndex = ($) => { + const value = canonicalNumericIndexString($); + if (value !== undefined) { + return Object.is(value, 0) || value > 0 && value < -1 >>> 0; + } else { + return false; + } +}; + +/** + * Returns whether the provided object is a collection. + * + * The definition of “collection” used by Piscēs is similar to + * Ecmascript’s definition of an arraylike object, but it differs in + * a few ways :— + * + * - It requires the provided value to be a proper object. + * + * - It requires the `length` property to be an integer corresponding + * to an integer index. + * + * - It requires the object to be concat‐spreadable, meaning it must + * either be an array or have `[Symbol.isConcatSpreadable]` be true. + */ +export const isCollection = ($) => { + if (!(isObject($) && "length" in $)) { + // The provided value is not an object or does not have a `length`. + return false; + } else { + try { + toIndex($.length); // will throw if `length` is not an index + return isConcatSpreadable($); + } catch { + return false; + } + } +}; + +/** + * Returns whether the provided value is spreadable during array + * concatenation. + * + * This is also used to determine which things should be treated as + * collections. + */ +export const isConcatSpreadable = ($) => { + if (!isObject($)) { + // The provided value is not an object. + return false; + } else { + // The provided value is an object. + return !!($[Symbol.isConcatSpreadable] ?? Array.isArray($)); + } +}; + +/** Returns whether the provided value is an integer index. */ +export const isIntegerIndex = ($) => { + const value = canonicalNumericIndexString($); + if (value !== undefined) { + return Object.is(value, 0) || + value > 0 && value <= MAX_SAFE_INTEGER; + } else { + return false; + } +}; + +/** + * Returns the length of the provided arraylike object. + * + * Will throw if the provided object is not arraylike. + * + * This produces larger lengths than can actually be stored in arrays, + * because no such restrictions exist on arraylike methods. Use + * `isIndex` to determine if a value is an actual array index. + */ +export const lengthOfArrayLike = ({ length }) => { + return toLength(length); +}; + +/** + * Converts the provided value to an array index, or throws an error if + * it is out of range. + */ +export const toIndex = ($) => { + const integer = Math.floor($); + if (isNaN(integer) || integer == 0) { + // The value is zero·like. + return 0; + } else { + // The value is not zero·like. + const clamped = toLength(integer); + if (clamped !== integer) { + // Clamping the value changes it. + throw new RangeError(`Piscēs: Index out of range: ${$}.`); + } else { + // The value is within appropriate bounds. + return integer; + } + } +}; + +/** Converts the provided value to a length. */ +export const toLength = ($) => { + const len = Math.floor($); + return isNaN(len) || len == 0 + ? 0 + : Math.max(Math.min(len, MAX_SAFE_INTEGER), 0); +}; diff --git a/deno.json b/deno.json new file mode 100644 index 0000000..e5f93e5 --- /dev/null +++ b/deno.json @@ -0,0 +1,4 @@ +{ + "fmt": { "options": { "lineWidth": 71 } }, + "lint": { "rules": { "exclude": ["no-irregular-whitespace"] } } +} diff --git a/dev-deps.js b/dev-deps.js new file mode 100644 index 0000000..49044c1 --- /dev/null +++ b/dev-deps.js @@ -0,0 +1,15 @@ +// ♓🌟 Piscēs ∷ dev-deps.js +// ==================================================================== +// +// Copyright © 2022 Lady [@ Lady’s Computer]. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +export { + assert, + assertEquals, + assertStrictEquals, + assertThrows, +} from "https://deno.land/std@0.134.0/testing/asserts.ts"; diff --git "a/i\302\267r\302\267i.js" "b/i\302\267r\302\267i.js" new file mode 100644 index 0000000..0892213 --- /dev/null +++ "b/i\302\267r\302\267i.js" @@ -0,0 +1,78 @@ +// ♓🌟 Piscēs ∷ i·r·i.js +// ==================================================================== +// +// Copyright © 2020, 2022 Lady [@ Lady’s Computer]. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +//deno-lint-ignore-file no-unused-vars + +const sub·delims = String.raw`[!\$&'()*+,;=]`; +const gen·delims = String.raw`[:/?#\[\]@]`; +const reserved = String.raw`${gen·delims}|${sub·delims}`; +const unreserved = String.raw`[A-Za-z0-9\-\._~]`; +const pct·encoded = String.raw`%[0-9A-Fa-f][0-9A-Fa-f]`; +const dec·octet = String.raw + `[0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5]`; +const IPv4address = String.raw + `(?:${dec·octet})\.(?:${dec·octet})\.(?:${dec·octet})\.(?:${dec·octet})`; +const h16 = String.raw`[0-9A-Fa-f]{1,4}`; +const ls32 = String.raw`(?:${h16}):(?:${h16})|${IPv4address}`; +const IPv6address = String.raw + `(?:(?:${h16}):){6}(?:${ls32})|::(?:(?:${h16}):){5}(?:${ls32})|(?:${h16})?::(?:(?:${h16}):){4}(?:${ls32})|(?:(?:(?:${h16}):){0,1}(?:${h16}))?::(?:(?:${h16}):){3}(?:${ls32})|(?:(?:(?:${h16}):){0,2}(?:${h16}))?::(?:(?:${h16}):){2}(?:${ls32})|(?:(?:(?:${h16}):){0,3}(?:${h16}))?::(?:${h16}):(?:${ls32})|(?:(?:(?:${h16}):){0,4}(?:${h16}))?::(?:${ls32})|(?:(?:(?:${h16}):){0,5}(?:${h16}))?::(?:${h16})|(?:(?:(?:${h16}):){0,6}(?:${h16}))?::`; +const IPvFuture = String.raw + `v[0-9A-Fa-f]{1,}\.(?:${unreserved}|${sub·delims}|:)`; +const IP·literal = String.raw`\[(?:${IPv6address}|${IPvFuture})\]`; +const port = String.raw`[0-9]*`; +const scheme = String.raw`[A-Za-z][A-Za-z0-9+\-\.]*`; +const iprivate = String.raw + `[\u{E000}-\u{F8FF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]`; +const ucschar = String.raw + `[\u{A0}-\u{D7FF}\u{F900}-\u{FDCF}\u{FDF0}-\u{FFEF}\u{10000}-\u{1FFFD}\u{20000}-\u{2FFFD}\u{30000}-\u{3FFFD}\u{40000}-\u{4FFFD}\u{50000}-\u{5FFFD}\u{60000}-\u{6FFFD}\u{70000}-\u{7FFFD}\u{80000}-\u{8FFFD}\u{90000}-\u{9FFFD}\u{A0000}-\u{AFFFD}\u{B0000}-\u{BFFFD}\u{C0000}-\u{CFFFD}\u{D0000}-\u{DFFFD}\u{E0000}-\u{EFFFD}]`; +const iunreserved = String.raw`[A-Za-z0-9\-\._~]|${ucschar}`; +const ipchar = String.raw + `${iunreserved}|${pct·encoded}|${sub·delims}|[:@]`; +const ifragment = String.raw`(?:${ipchar}|[/?])*`; +const iquery = String.raw`(?:${ipchar}|${iprivate}|[/?])*`; +const isegment·nz·nc = String.raw + `(?:${iunreserved}|${pct·encoded}|${sub·delims}|@)+`; +const isegment·nz = String.raw`(?:${ipchar})+`; +const isegment = String.raw`(?:${ipchar})*`; +const ipath·empty = String.raw``; +const ipath·rootless = String.raw + `(?:${isegment·nz})(?:/(?:${isegment}))*`; +const ipath·noscheme = String.raw + `(?:${isegment·nz·nc})(?:/(?:${isegment}))*`; +const ipath·absolute = String.raw + `/(?:(?:${isegment·nz})(?:/(?:${isegment}))*)?`; +const ipath·abempty = String.raw`(?:/(?:${isegment}))*`; +const ipath = String.raw + `${ipath·abempty}|${ipath·absolute}|${ipath·noscheme}|${ipath·rootless}|${ipath·empty}`; +const ireg·name = String.raw + `(?:${iunreserved}|${pct·encoded}|${sub·delims})*`; +const ihost = String.raw`${IP·literal}|${IPv4address}|${ireg·name}`; +const iuserinfo = String.raw + `(?:${iunreserved}|${pct·encoded}|${sub·delims}|:)*`; +const iauthority = String.raw + `(?:(${iuserinfo})@)?(${ihost})(?::(${port}))?`; +const irelative·part = String.raw + `//(${iauthority})(${ipath·abempty})|(${ipath·absolute})|(${ipath·noscheme})|(${ipath·empty})`; +const irelative·ref = String.raw + `(${irelative·part})(?:\?(${iquery}))?(?:#(${ifragment}))?`; +const ihier·part = String.raw + `//(${iauthority})(${ipath·abempty})|(${ipath·absolute})|(${ipath·rootless})|(${ipath·empty})`; +const absolute·IRI = String.raw + `(${scheme}):(${ihier·part})(?:\?(${iquery}))?`; +const IRI = String.raw + `(${scheme}):(${ihier·part})(?:\?(${iquery}))?(?:#(${ifragment}))?`; +const IRI·reference = String.raw`(${IRI})|(${irelative·ref})`; + +export const isI·R·I = ($) => + typeof $ == "string" && isI·R·I.regExp.test($); +Object.defineProperty(isI·R·I, "regExp", { + configurable: true, + enumerable: false, + get: () => new RegExp(`^(?:${IRI})$`, "u"), +}); diff --git a/mod.js b/mod.js new file mode 100644 index 0000000..a25bc1e --- /dev/null +++ b/mod.js @@ -0,0 +1,14 @@ +// ♓🌟 Piscēs ∷ mod.js +// ==================================================================== +// +// Copyright © 2020–2022 Lady [@ Lady’s Computer]. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +export * from "./base64.js"; +export * from "./collection.js"; +export * from "./i·r·i.js"; +export * from "./numeric.js"; +export * from "./object.js"; diff --git a/numeric.js b/numeric.js new file mode 100644 index 0000000..2c1a66f --- /dev/null +++ b/numeric.js @@ -0,0 +1,11 @@ +// ♓🌟 Piscēs ∷ numeric.js +// ==================================================================== +// +// Copyright © 2022 Lady [@ Lady’s Computer]. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +/** 2^53 − 1. */ +export const MAX_SAFE_INTEGER = Number((1n << 53n) - 1n); diff --git a/object.js b/object.js new file mode 100644 index 0000000..502207e --- /dev/null +++ b/object.js @@ -0,0 +1,42 @@ +// ♓🌟 Piscēs ∷ object.js +// ==================================================================== +// +// Copyright © 2022 Lady [@ Lady’s Computer]. +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at . + +/** Returns whether the provided value is a constructor. */ +export const isConstructor = ($) => { + if (!isObject($)) { + // The provided value is not an object. + return false; + } else { + // The provided value is an object. + try { + Reflect.construct( + function () {}, + [], + $, + ); // will throw if $ is not a constructor + return true; + } catch { + return false; + } + } +}; + +/** Returns whether the provided value is an object. */ +export const isObject = ($) => { + return $ !== null && + (typeof $ == "function" || typeof $ == "object"); +}; + +/** + * Returns whether the provided object inherits from the prototype of + * the provided function. + */ +export const ordinaryHasInstance = Function.prototype.call.bind( + Function.prototype[Symbol.hasInstance], +);