summaryrefslogtreecommitdiff
path: root/deps/v8/tools/turbolizer/src/selection/selection-map.ts
blob: ff401fe8a32e6086b6caa3fb5e02af6c0db3329d (plain)
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
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import { GraphNode } from "../phases/graph-phase/graph-node";

export class SelectionMap {
  selection: Map<string, any>;
  stringKey: (obj: any) => string;
  originStringKey: (node: GraphNode) => string;

  constructor(stringKeyFnc, originStringKeyFnc?) {
    this.selection = new Map<string, any>();
    this.stringKey = stringKeyFnc;
    this.originStringKey = originStringKeyFnc;
  }

  public isEmpty(): boolean {
    return this.selection.size == 0;
  }

  public clear(): void {
    this.selection = new Map<string, any>();
  }

  public select(items: Iterable<any>, isSelected?: boolean): void {
    for (const item of items) {
      if (item === undefined) continue;
      if (isSelected === undefined) {
        isSelected = !this.selection.has(this.stringKey(item));
      }
      if (isSelected) {
        this.selection.set(this.stringKey(item), item);
      } else {
        this.selection.delete(this.stringKey(item));
      }
    }
  }

  public isSelected(obj: any): boolean {
    return this.selection.has(this.stringKey(obj));
  }

  public isKeySelected(key: string): boolean {
    return this.selection.has(key);
  }

  public selectedKeys(): Set<string> {
    const result = new Set<string>();
    for (const key of this.selection.keys()) {
      result.add(key);
    }
    return result;
  }

  public detachSelection(): Map<string, any> {
    const result = this.selection;
    this.clear();
    return result;
  }

  [Symbol.iterator]() { return this.selection.values(); }
}