Skip to content

Commit 3c055d8

Browse files
committed
Initial Set implementation
1 parent 543cd37 commit 3c055d8

File tree

2 files changed

+77
-2
lines changed

2 files changed

+77
-2
lines changed

src/lualib/Map.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ class Map<TKey, TValue> {
2424
public delete(key: TKey): boolean {
2525
const contains = this.has(key);
2626
if (contains) {
27-
this.size = this.size - 1;
27+
this.size--;
2828
}
2929
this.items[key as any] = undefined;
3030
return contains;
@@ -63,7 +63,7 @@ class Map<TKey, TValue> {
6363

6464
public set(key: TKey, value: TValue): Map<TKey, TValue> {
6565
if (!this.has(key)) {
66-
this.size = this.size + 1;
66+
this.size++;
6767
}
6868
this.items[key as any] = value;
6969
return this;

src/lualib/Set.ts

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
class Set<TValue> {
2+
public size: number;
3+
4+
private items: {[key: string]: boolean}; // Key type is actually TValue
5+
6+
public Set(other: any) {
7+
this.items = {};
8+
this.size = 0;
9+
10+
if (other) {
11+
this.size = other.size;
12+
for (const value of other.values()) {
13+
this.items[value] = true;
14+
}
15+
}
16+
}
17+
18+
public add(value: TValue) {
19+
if (!this.has(value)) {
20+
this.size++;
21+
}
22+
this.items[value as any] = true;
23+
return this;
24+
}
25+
26+
public clear(): void {
27+
this.items = {};
28+
this.size = 0;
29+
return;
30+
}
31+
32+
public delete(value: TValue): boolean {
33+
const contains = this.has(value);
34+
if (contains) {
35+
this.size--;
36+
}
37+
this.items[value as any] = undefined;
38+
return contains;
39+
}
40+
41+
public entries(): Array<[TValue, TValue]> {
42+
const out = [];
43+
for (const key in this.items) {
44+
out[out.length] = [key, key];
45+
}
46+
return out;
47+
}
48+
49+
public forEach(callback: (value: TValue, key: TValue, set: Set<TValue>) => any): void {
50+
for (const key in this.items) {
51+
callback(key as any, key as any, this);
52+
}
53+
return;
54+
}
55+
56+
public has(value: TValue): boolean {
57+
return this.items[value as any] === true;
58+
}
59+
60+
public keys(): TValue[] {
61+
const out = [];
62+
for (const key in this.items) {
63+
out[out.length] = key;
64+
}
65+
return out;
66+
}
67+
68+
public values(): TValue[] {
69+
const out = [];
70+
for (const key in this.items) {
71+
out[out.length] = key;
72+
}
73+
return out;
74+
}
75+
}

0 commit comments

Comments
 (0)