git ssb

0+

wanderer🌟 / lockmap



Tree: eb6fd4434e06cb5f0151897c665d531a4c84151e

Files: eb6fd4434e06cb5f0151897c665d531a4c84151e / index.js

920 bytesRaw
1module.exports = class LockMap {
2 /**
3 * Creates a new instance of LockMap
4 */
5 constructor () {
6 this._map = new Map()
7
8 const methods = ['clear', 'delete', 'entries', 'forEach', 'get', 'has', 'keys', 'values', Symbol.iterator]
9 const self = this
10 methods.forEach(method => {
11 self[method] = function () {
12 return self._map[method].apply(self._map, arguments)
13 }
14 })
15 }
16
17 /**
18 * Creates a lock on a given ID and returns a resolve function to unlock the
19 * lock
20 * @param {*} id
21 * @return {Function} the resolve function to call once it to unlock
22 */
23 lock (id) {
24 let r
25 const promise = new Promise((resolve, reject) => {
26 r = resolve
27 })
28 promise.then(() => {
29 this._map.delete(id)
30 })
31 this._map.set(id, promise)
32 return r
33 }
34
35 get size () {
36 return this._map.size
37 }
38
39 get [Symbol.toStringTag] () {
40 return 'LockMap'
41 }
42}
43

Built with git-ssb-web