diff options
author | 2022-03-07 15:36:22 -0600 | |
---|---|---|
committer | 2022-03-07 15:36:22 -0600 | |
commit | f18ee36dc0abdc5c8ec87734de7962966d16fe65 (patch) | |
tree | c01a7034186cb0bbe5e1d042f4a5dd09bad21ed5 /packages/webapi/src/lib/RelativeIndexingMethod.ts | |
parent | 10a9c3412b4f6e8607687a74eafdb150d3222047 (diff) | |
download | astro-f18ee36dc0abdc5c8ec87734de7962966d16fe65.tar.gz astro-f18ee36dc0abdc5c8ec87734de7962966d16fe65.tar.zst astro-f18ee36dc0abdc5c8ec87734de7962966d16fe65.zip |
Add `@astrojs/webapi` package (#2729)@astrojs/webapi@0.11.0
* chore: add @astrojs/webapi
* chore: update package.json
* fix: update file case
* fix: remove lowercase file
* chore: update tests to use mocha
* chore: update LICENSE
Diffstat (limited to 'packages/webapi/src/lib/RelativeIndexingMethod.ts')
-rw-r--r-- | packages/webapi/src/lib/RelativeIndexingMethod.ts | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/packages/webapi/src/lib/RelativeIndexingMethod.ts b/packages/webapi/src/lib/RelativeIndexingMethod.ts new file mode 100644 index 000000000..56627dfc3 --- /dev/null +++ b/packages/webapi/src/lib/RelativeIndexingMethod.ts @@ -0,0 +1,32 @@ +type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array + +export const at = { + at<T extends Array<any> | string | TypedArray>(this: T, index: number) { + index = Math.trunc(index) || 0 + + if (index < 0) index += this.length; + + if (index < 0 || index >= this.length) return undefined; + + return this[index]; + } +}.at + +export const initRelativeIndexingMethod = (target: any, exclude: Set<string>) => { + if (exclude.has('at')) return + + const Classes = [] + + if (!exclude.has('TypedArray')) Classes.push(Object.getPrototypeOf(target.Int8Array || globalThis.Int8Array)) + if (!exclude.has('Array')) Classes.push(target.Array || globalThis.Array) + if (!exclude.has('String')) Classes.push(target.String || globalThis.String) + + for (const Class of Classes) { + if (!Class.prototype.at) Object.defineProperty(Class.prototype, 'at', { + value: at, + writable: true, + enumerable: false, + configurable: true + }) + } +} |