1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | module.exports = class DataMap {
|
7 |
|
8 | constructor (data) {
|
9 | this._data = data || {};
|
10 | }
|
11 |
|
12 | has (key) {
|
13 | return Object.prototype.hasOwnProperty.call(this._data, key);
|
14 | }
|
15 |
|
16 | get (key, defaults) {
|
17 | return this.has(key) ? this._data[key] : defaults;
|
18 | }
|
19 |
|
20 | set (key, value) {
|
21 | this._data[key] = value;
|
22 | return this;
|
23 | }
|
24 |
|
25 | push (key, value) {
|
26 | if (Array.isArray(this._data[key])) {
|
27 | this._data[key].push(value);
|
28 | } else {
|
29 | this._data[key] = [value];
|
30 | }
|
31 | return this;
|
32 | }
|
33 |
|
34 | unset (key) {
|
35 | delete this._data[key];
|
36 | }
|
37 |
|
38 | clear () {
|
39 | this._data = {};
|
40 | }
|
41 |
|
42 | assign (data) {
|
43 | data = data instanceof DataMap ? data._data : data;
|
44 | Object.assign(this._data, data);
|
45 | }
|
46 |
|
47 | keys () {
|
48 | return Object.keys(this._data);
|
49 | }
|
50 |
|
51 | values () {
|
52 | return Object.values(this._data);
|
53 | }
|
54 |
|
55 | entries () {
|
56 | return Object.entries(this._data);
|
57 | }
|
58 |
|
59 | size () {
|
60 | return this.values().length;
|
61 | }
|
62 |
|
63 | each () {
|
64 | return this.forEach(...arguments);
|
65 | }
|
66 |
|
67 | forEach (handler, context) {
|
68 | for (const item of this.values()) {
|
69 | handler.call(context, item)
|
70 | }
|
71 | return this;
|
72 | }
|
73 |
|
74 | filter (handler, context) {
|
75 | const result = [];
|
76 | for (const item of this.values()) {
|
77 | if (handler.call(context, item)) {
|
78 | result.push(item);
|
79 | }
|
80 | }
|
81 | return result;
|
82 | }
|
83 |
|
84 | map (handler, context) {
|
85 | const result = [];
|
86 | for (const item of this.values()) {
|
87 | result.push(handler.call(context, item));
|
88 | }
|
89 | return result;
|
90 | }
|
91 |
|
92 | sort (handler) {
|
93 | return this.values().sort(handler);
|
94 | }
|
95 |
|
96 | [Symbol.iterator] () {
|
97 | return this.values()[Symbol.iterator]();
|
98 | }
|
99 | }; |
\ | No newline at end of file |