Files: 32aeaca5a546e28da16423548ecc95a2efd17e77 / index.js
1323 bytesRaw
1 | module.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, type) { |
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 | * @param {Object} type - optional, a contructor that the retreived object should be an instance of |
23 | * @return {*} |
24 | */ |
25 | get (ref, type) { |
26 | const obj = this._map[ref] |
27 | if (obj === undefined || (type && type !== obj.constructor)) { |
28 | throw new Error('invalid referance') |
29 | } |
30 | return obj |
31 | } |
32 | |
33 | /** |
34 | * deletes an object given a referance as an int |
35 | * @param {integer} |
36 | * @return {boolean} whether or not the object was deleted |
37 | */ |
38 | delete (ref) { |
39 | delete this._map[ref] |
40 | } |
41 | |
42 | /** |
43 | * clears the referance map of a objects |
44 | */ |
45 | clear () { |
46 | this._map = [] |
47 | } |
48 | |
49 | /** |
50 | * returns the number of items in the refernace map |
51 | * @return {integer} |
52 | */ |
53 | get size () { |
54 | return this._map.length |
55 | } |
56 | |
57 | /** |
58 | * tests wether a given referance is valid or not |
59 | * @return {boolean} |
60 | */ |
61 | has (ref) { |
62 | const obj = this._map[ref] |
63 | return obj !== undefined |
64 | } |
65 | } |
66 |
Built with git-ssb-web