-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathiteratorMixin.ts
86 lines (82 loc) · 2.32 KB
/
iteratorMixin.ts
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import { createFastIterator } from "./createIterator.ts";
function checkRequiredArguments(
arg: any[] | IArguments | number,
required: number,
prefix?: string,
) {
if ((typeof arg === "number" ? arg : (arg = arg.length)) < required) {
const errMsg = `${prefix ? prefix + ": " : ""}${required} argument${
required === 1 ? "" : "s"
} required, but only ${arg} present.`;
throw new TypeError(errMsg);
}
}
function brandCheck(self: any, instance: any) {
if (!(self instanceof instance)) {
throw new TypeError("Illegal invocation");
}
}
export function iteratorMixin(
name: string,
object: any,
internalIteratorSymbol: symbol,
keyIndex: string | number = 0,
valueIndex: string | number = 1,
) {
const createIterator = createFastIterator(name, internalIteratorSymbol, keyIndex, valueIndex);
const properties = {
keys: {
writable: true,
enumerable: true,
configurable: true,
value: function keys() {
brandCheck(this, object);
return createIterator(this, "key");
},
},
values: {
writable: true,
enumerable: true,
configurable: true,
value: function values() {
brandCheck(this, object);
return createIterator(this, "value");
},
},
entries: {
writable: true,
enumerable: true,
configurable: true,
value: function entries() {
brandCheck(this, object);
return createIterator(this, "key+value");
},
},
forEach: {
writable: true,
enumerable: true,
configurable: true,
value: function forEach(callbackfn: any, thisArg = globalThis) {
brandCheck(this, object);
checkRequiredArguments(arguments, 1, `Failed to execute 'forEach' on '${name}'`);
if (typeof callbackfn !== "function") {
throw new TypeError(
`Failed to execute 'forEach' on '${name}': parameter 1 is not of type 'Function'.`,
);
}
for (const { 0: key, 1: value } of createIterator(this, "key+value")) {
callbackfn.call(thisArg, value, key, this);
}
},
},
};
return Object.defineProperties(object.prototype, {
...properties,
[Symbol.iterator]: {
writable: true,
enumerable: false,
configurable: true,
value: properties.entries.value,
},
});
}