git ssb

0+

wanderer🌟 / referenceMap



Tree: 6fa996e4863669d7a6dd929420b068c7d02ae185

Files: 6fa996e4863669d7a6dd929420b068c7d02ae185 / index.js

1544 bytesRaw
1module.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][this.intRefProp]
47 delete this._map[ref]
48 }
49
50 /**
51 * clears the referance map of a objects
52 */
53 clear () {
54 this.intRefProp = Symbol('int')
55 this._map = []
56 }
57
58 /**
59 * returns the number of items in the refernace map
60 * @return {integer}
61 */
62 get size () {
63 return this._map.length
64 }
65
66 /**
67 * tests wether a given referance is valid or not
68 * @return {boolean}
69 */
70 has (ref) {
71 const obj = this._map[ref]
72 return obj !== undefined
73 }
74}
75

Built with git-ssb-web