forked from rome/tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArraySet.ts
More file actions
71 lines (62 loc) · 1.76 KB
/
Copy pathArraySet.ts
File metadata and controls
71 lines (62 loc) · 1.76 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
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
* Copyright 2011 Mozilla Foundation and contributors
* Licensed under the New BSD license. See LICENSE or:
* http://opensource.org/licenses/BSD-3-Clause
*/
/**
* A data structure which is a combination of an array and a set. Adding a new
* member is O(1), testing for membership is O(1), and finding the index of an
* element is O(1). Removing elements from the set is not supported. Only
* strings are supported for membership.
*/
export default class ArraySet {
constructor() {
this.array = [];
this.set = new Map();
}
private array: Array<string>;
private set: Map<string, number>;
/**
* Add the given string to this set.
*/
public add(str: string, allowDuplicates?: boolean): void {
const isDuplicate = this.has(str);
const idx = this.array.length;
if (!isDuplicate || allowDuplicates === true) {
this.array.push(str);
}
if (!isDuplicate) {
this.set.set(str, idx);
}
}
/**
* Is the given string a member of this set?
*/
private has(str: string): boolean {
return this.set.has(str);
}
/**
* What is the index of the given string in the array?
*/
public indexOf(str: string): number {
const idx = this.set.get(str);
if (idx === undefined || idx < 0) {
throw new Error(`${str} is not in the set`);
}
return idx;
}
/**
* Returns the array representation of this set (which has the proper indices
* indicated by indexOf). Note that this is a copy of the internal array used
* for storing the members so that no one can mess with internal state.
*/
public toArray(): Array<string> {
return this.array.slice();
}
}