Files: baff2862fe1006abf980eeb24ba65b81d4f54012 / index.js
992 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) { |
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) { |
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 |
Built with git-ssb-web