git ssb

0+

wanderer🌟 / referenceMap



Tree: b3287b5da8e1c252351f41e6be8999482a580f5e

Files: b3287b5da8e1c252351f41e6be8999482a580f5e / index.js

1758 bytesRaw
1module.exports = class ReferanceMap {
2 /**
3 * Handle mapping arbitrary JS object to ints
4 */
5 constructor () {
6 this.intRefProp = Symbol('int')
7 this._map = []
8 }
9
10 /**
11 * Adds an object to the reference map returning an int to be used as a
12 * reference
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 reference as an int
28 * @param {integer} ref
29 * @param {Object} type - optional
30 * @return {*}
31 */
32 get (ref, typeCheck) {
33 const result = this._map[ref]
34 if (result === undefined) {
35 throw new Error(`invalid reference "${ref}". Object doesn't exist`)
36 } else if (typeCheck && result.type !== typeCheck) {
37 throw new Error(`invalid reference "${ref}". Expected type: "${typeCheck}" actual type: "${result.type}"`)
38 }
39 return result.obj
40 }
41
42 /**
43 * deletes an object given a reference as an int
44 * @param {integer}
45 * @return {boolean} whether or not the object was deleted
46 */
47 delete (ref) {
48 delete this._map[ref].obj[this.intRefProp]
49 delete this._map[ref]
50 }
51
52 /**
53 * clears the reference map of a objects
54 */
55 clear () {
56 this._map.forEach(el => {
57 delete el.obj[this.intRefProp]
58 })
59 this._map = []
60 }
61
62 /**
63 * returns the number of items in the reference map
64 * @return {integer}
65 */
66 get size () {
67 return this._map.length
68 }
69
70 /**
71 * tests whether a given reference is valid or not
72 * @return {boolean}
73 */
74 has (ref) {
75 const obj = this._map[ref]
76 return obj !== undefined
77 }
78}
79

Built with git-ssb-web