git ssb

0+

wanderer🌟 / referenceMap



Tree: 9e8ae7783fd0d457d00c5e5a8c0201dcf6f23983

Files: 9e8ae7783fd0d457d00c5e5a8c0201dcf6f23983 / index.js

1171 bytesRaw
1module.exports = class ReferanceMap {
2 /**
3 * Handle mapping arbitary JS object to ints
4 */
5 constructor () {
6 this._map = []
7 }
8
9 /**
10 * Adds an object to the referance map returning an int to be used as a
11 * referance
12 * @param {*} obj
13 * @return {integer}
14 */
15 add (obj) {
16 return this._map.push(obj) - 1
17 }
18
19 /**
20 * gets a POJO given a refernce as an int
21 * @param {integer} ref
22 * @return {*}
23 */
24 get (ref) {
25 const obj = this._map[ref]
26 if (obj === undefined) {
27 throw new Error('invalid referance')
28 }
29 return obj
30 }
31
32 /**
33 * deletes an object given a referance as an int
34 * @param {integer}
35 * @return {boolean} whether or not the object was deleted
36 */
37 delete (ref) {
38 delete this._map[ref]
39 }
40
41 /**
42 * clears the referance map of a objects
43 */
44 clear () {
45 this._map = []
46 }
47
48 /**
49 * returns the number of items in the refernace map
50 * @return {integer}
51 */
52 get size () {
53 return this._map.length
54 }
55
56 /**
57 * tests wether a given referance is valid or not
58 * @return {boolean}
59 */
60 has (ref) {
61 const obj = this._map[ref]
62 return obj !== undefined
63 }
64}
65

Built with git-ssb-web