Files: 712a65040746cdf61fd9958556f7327af8bd08c5 / index.js
1586 bytesRaw
1 | module.exports = class ReferanceMap { |
2 | /** |
3 | * Handle mapping arbitary JS object to ints |
4 | */ |
5 | constructor () { |
6 | this.intRefProp = Symbol('int') |
7 | this._map = [] |
8 | } |
9 | |
10 | /** |
11 | * Adds an object to the referance map returning an int to be used as a |
12 | * referance |
13 | * @param {*} obj |
14 | * @param {*} type - optional |
15 | * @return {integer} |
16 | */ |
17 | add (obj, type) { |
18 | let ref = obj[this.intRefProp] |
19 | if (ref === undefined) { |
20 | ref = this._map.push({obj, type}) - 1 |
21 | obj[this.intRefProp] = ref |
22 | } |
23 | return ref |
24 | } |
25 | |
26 | /** |
27 | * gets a POJO given a refernce as an int |
28 | * @param {integer} ref |
29 | * @param {Object} type - optional |
30 | * @return {*} |
31 | */ |
32 | get (ref, typeCheck) { |
33 | const {obj, type} = this._map[ref] |
34 | if (obj === undefined || (typeCheck && type !== typeCheck)) { |
35 | throw new Error('invalid referance') |
36 | } |
37 | return obj |
38 | } |
39 | |
40 | /** |
41 | * deletes an object given a referance as an int |
42 | * @param {integer} |
43 | * @return {boolean} whether or not the object was deleted |
44 | */ |
45 | delete (ref) { |
46 | delete this._map[ref].obj[this.intRefProp] |
47 | delete this._map[ref] |
48 | } |
49 | |
50 | /** |
51 | * clears the referance map of a objects |
52 | */ |
53 | clear () { |
54 | this._map.forEach(el => { |
55 | delete el.obj[this.intRefProp] |
56 | }) |
57 | this._map = [] |
58 | } |
59 | |
60 | /** |
61 | * returns the number of items in the refernace map |
62 | * @return {integer} |
63 | */ |
64 | get size () { |
65 | return this._map.length |
66 | } |
67 | |
68 | /** |
69 | * tests wether a given referance is valid or not |
70 | * @return {boolean} |
71 | */ |
72 | has (ref) { |
73 | const obj = this._map[ref] |
74 | return obj !== undefined |
75 | } |
76 | } |
77 |
Built with git-ssb-web