Files: b301e093c4c3eac192e197600af914e9a6270af1 / index.js
1465 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] |
47 | } |
48 | |
49 | /** |
50 | * clears the referance map of a objects |
51 | */ |
52 | clear () { |
53 | this._map = [] |
54 | } |
55 | |
56 | /** |
57 | * returns the number of items in the refernace map |
58 | * @return {integer} |
59 | */ |
60 | get size () { |
61 | return this._map.length |
62 | } |
63 | |
64 | /** |
65 | * tests wether a given referance is valid or not |
66 | * @return {boolean} |
67 | */ |
68 | has (ref) { |
69 | const obj = this._map[ref] |
70 | return obj !== undefined |
71 | } |
72 | } |
73 |
Built with git-ssb-web