Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
*
* SPDX-License-Identifier: MIT
*/
// Before everything else so the shims are in place for module initialisation.
import "./polyfills";
// The CSS entry point: declares the cascade-layer order Panda's PostCSS
// plugin fills, and the vendor-layer imports. First so app styles cascade
// after it.
Expand Down
39 changes: 39 additions & 0 deletions src/polyfills.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/**
* (c) 2026, Micro:bit Educational Foundation and contributors
*
* SPDX-License-Identifier: MIT
*/
import { describe, expect, it } from "vitest";
import { at } from "./polyfills";

describe("at", () => {
const call = <T>(target: ArrayLike<T>, index: number) =>
at.call(target, index) as T | undefined;

it("indexes from the start", () => {
expect(call(["a", "b", "c"], 0)).toEqual("a");
expect(call(["a", "b", "c"], 2)).toEqual("c");
});

it("indexes from the end", () => {
expect(call(["a", "b", "c"], -1)).toEqual("c");
expect(call(["a", "b", "c"], -3)).toEqual("a");
});

it("returns undefined when out of range", () => {
expect(call(["a"], 1)).toBeUndefined();
expect(call(["a"], -2)).toBeUndefined();
expect(call([], -1)).toBeUndefined();
});

it("truncates and coerces the index", () => {
expect(call(["a", "b", "c"], 1.9)).toEqual("b");
expect(call(["a", "b", "c"], -1.9)).toEqual("c");
expect(call(["a", "b", "c"], NaN)).toEqual("a");
expect(call(["a", "b", "c"], undefined as unknown as number)).toEqual("a");
});

it("works on strings", () => {
expect(call("abc", -1)).toEqual("c");
});
});
21 changes: 21 additions & 0 deletions src/polyfills.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/**
* (c) 2026, Micro:bit Educational Foundation and contributors
*
* SPDX-License-Identifier: MIT
*/
// Remove when we drop Safari < 15.4.
// Also seen helping some v old Chrome but not reasonable to maintain support here past when we drop older Safari.
export function at<T>(this: ArrayLike<T>, index: number): T | undefined {
const i = Math.trunc(index) || 0;
return this[i < 0 ? this.length + i : i];
}

for (const proto of [Array.prototype, String.prototype]) {
if (!(proto as { at?: unknown }).at) {
Object.defineProperty(proto, "at", {
value: at,
writable: true,
configurable: true,
});
}
}