-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathpolyfills.ts
More file actions
59 lines (51 loc) · 1.86 KB
/
polyfills.ts
File metadata and controls
59 lines (51 loc) · 1.86 KB
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Temporal as PolyfillTemporal } from "@js-temporal/polyfill";
declare global {
// type polyfill for Math.sumPrecise (currently in stage 2):
// https://github.com/tc39/proposal-math-sum
// Remove this as soon as it is stable
interface Math {
sumPrecise: (values: number[]) => number;
}
// https://github.com/tc39/proposal-upsert
interface Map<K, V> {
getOrInsert(key: K, defaultValue: V): V;
getOrInsertComputed<TK extends K>(key: TK, callbackFunction: (key: TK) => V): V;
}
}
globalThis.Temporal = PolyfillTemporal as typeof Temporal;
// TODO: Remove this once temporal is available in Node.js, see: https://github.com/nodejs/node/issues/57127
if (typeof Date.prototype.toTemporalInstant !== "function") {
Date.prototype.toTemporalInstant = function () {
return Temporal.Instant.fromEpochMilliseconds(this.getTime());
};
}
if (typeof Math.sumPrecise !== "function") {
// intentionally very cheap implementation. But does the thing.
Math.sumPrecise = (values: number[]) => values.reduce((a, b) => a + b, 0);
}
// https://github.com/tc39/proposal-upsert
if (typeof Map.prototype.getOrInsert === "undefined") {
Map.prototype.getOrInsert = function <K, V>(this: Map<K, V>, key: K, defaultValue: V): V {
const v = this.get(key);
if (v !== undefined) {
return v;
}
this.set(key, defaultValue);
return defaultValue;
};
}
if (typeof Map.prototype.getOrInsertComputed === "undefined") {
Map.prototype.getOrInsertComputed = function <K, V>(
this: Map<K, V>,
key: K,
callbackFunction: (key: K) => V,
): V {
const v = this.get(key);
if (v !== undefined) {
return v;
}
const defaultValue = callbackFunction(key);
this.set(key, defaultValue);
return defaultValue;
};
}