Skip to content

Commit

Permalink
Add polyfill for Array.prototype.with()
Browse files Browse the repository at this point in the history
  • Loading branch information
theBGuy committed Jan 22, 2025
1 parent 4c1e685 commit 4a777e3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
23 changes: 23 additions & 0 deletions d2bs/kolbot/libs/Polyfill.js
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,29 @@ if (!Array.prototype.toSpliced) {
};
}

/**
* @description The with() method of Array instances is the copying version of using the bracket notation to change the value of a given index.
* It returns a new array with the element at the given index replaced with the given value.
* @param {number} index - Zero-based index at which to change the array, converted to an integer.
* @param {*} value - Any value to be assigned to the given index.
* @returns {Array} A new array with the element at index replaced with value.
* @throws {RangeError} If index >= array.length or index < -array.length.
*/
if (!Array.prototype.with) {
Array.prototype.with = function (index, value) {
const len = this.length;
const relativeIndex = index < 0 ? len + index : index;

if (relativeIndex < 0 || relativeIndex >= len) {
throw new RangeError("Index out of range");
}

const newArray = this.slice();
newArray[relativeIndex] = value;
return newArray;
};
}

/**
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Object Polyfills ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
Expand Down
9 changes: 9 additions & 0 deletions d2bs/kolbot/sdk/globals.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,15 @@ declare global {
* @returns {Array<T>} A new array with the removed elements and optionally added elements.
*/
toSpliced(start: number, deleteCount?: number, ...items: T[]): T[];
/**
* @description The with() method of Array instances is the copying version of using the bracket notation to change the value of a given index.
* It returns a new array with the element at the given index replaced with the given value.
* @param {number} index - Zero-based index at which to change the array, converted to an integer.
* @param {*} value - Any value to be assigned to the given index.
* @returns {Array} A new array with the element at index replaced with value.
* @throws {RangeError} If index >= array.length or index < -array.length.
*/
with(index: number, value: T): T[];
}

interface String {
Expand Down

0 comments on commit 4a777e3

Please sign in to comment.