summaryrefslogtreecommitdiff
path: root/qutebrowser/javascript/quirks/array_at.user.js
blob: 1e42184390b3c729ee0732aa467e0c855361a2d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// ==UserScript==
// @include https://*.linkedin.com/*
// @include https://test.qutebrowser.org/*
// ==/UserScript==
//
// Based on: https://github.com/tc39/proposal-relative-indexing-method#polyfill

/* eslint-disable no-invalid-this */

"use strict";

(function() {
    function at(idx) {
        // ToInteger() abstract op
        let n = Math.trunc(idx) || 0;
        // Allow negative indexing from the end
        if (n < 0) {
            n += this.length;
        }
        // OOB access is guaranteed to return undefined
        if (n < 0 || n >= this.length) {
            return undefined;
        }
        // Otherwise, this is just normal property access
        return this[n];
    }

    const TypedArray = Reflect.getPrototypeOf(Int8Array);
    for (const type of [Array, String, TypedArray]) {
        Object.defineProperty(
            type.prototype,
            "at",
            {
                "value": at,
                "writable": true,
                "enumerable": false,
                "configurable": true,
            }
        );
    }
})();