es6-collections.js
2.51 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
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/**
* A collection of shims that provide minimal functionality of the ES6 collections.
*
* These implementations are not meant to be used outside of the ResizeObserver
* modules as they cover only a limited range of use cases.
*/
/* eslint-disable require-jsdoc, valid-jsdoc */
const MapShim = (() => {
if (typeof Map !== 'undefined') {
return Map;
}
/**
* Returns index in provided array that matches the specified key.
*
* @param {Array<Array>} arr
* @param {*} key
* @returns {number}
*/
function getIndex(arr, key) {
let result = -1;
arr.some((entry, index) => {
if (entry[0] === key) {
result = index;
return true;
}
return false;
});
return result;
}
return class {
constructor() {
this.__entries__ = [];
}
/**
* @returns {boolean}
*/
get size() {
return this.__entries__.length;
}
/**
* @param {*} key
* @returns {*}
*/
get(key) {
const index = getIndex(this.__entries__, key);
const entry = this.__entries__[index];
return entry && entry[1];
}
/**
* @param {*} key
* @param {*} value
* @returns {void}
*/
set(key, value) {
const index = getIndex(this.__entries__, key);
if (~index) {
this.__entries__[index][1] = value;
} else {
this.__entries__.push([key, value]);
}
}
/**
* @param {*} key
* @returns {void}
*/
delete(key) {
const entries = this.__entries__;
const index = getIndex(entries, key);
if (~index) {
entries.splice(index, 1);
}
}
/**
* @param {*} key
* @returns {void}
*/
has(key) {
return !!~getIndex(this.__entries__, key);
}
/**
* @returns {void}
*/
clear() {
this.__entries__.splice(0);
}
/**
* @param {Function} callback
* @param {*} [ctx=null]
* @returns {void}
*/
forEach(callback, ctx = null) {
for (const entry of this.__entries__) {
callback.call(ctx, entry[1], entry[0]);
}
}
};
})();
export {MapShim as Map};