Skip to content

Commit 40b1881

Browse files
authored
Implement has() and hasMany() (#25)
Ref: Level/community#142 Category: addition
1 parent 3a29a91 commit 40b1881

File tree

1 file changed

+57
-1
lines changed

1 file changed

+57
-1
lines changed

index.js

Lines changed: 57 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,9 @@ class BrowserLevel extends AbstractLevel {
2727
snapshots: false,
2828
createIfMissing: false,
2929
errorIfExists: false,
30-
seek: true
30+
seek: true,
31+
has: true,
32+
getSync: false
3133
}, forward)
3234

3335
if (typeof location !== 'string' || location === '') {
@@ -160,6 +162,60 @@ class BrowserLevel extends AbstractLevel {
160162
return values
161163
}
162164

165+
async _has (key, options) {
166+
const store = this[kStore]('readonly')
167+
const request = store.count(key)
168+
const count = await this[kOnComplete](request)
169+
170+
return count === 1
171+
}
172+
173+
async _hasMany (keys, options) {
174+
const store = this[kStore]('readonly')
175+
const iterator = keys.values()
176+
177+
// Consume the iterator with N parallel worker bees
178+
const n = Math.min(16, keys.length)
179+
const bees = new Array(n)
180+
const results = new Array(keys.length)
181+
182+
let keyIndex = 0
183+
let abort = false
184+
185+
const bee = async function () {
186+
try {
187+
for (const key of iterator) {
188+
if (abort) break
189+
190+
const resultIndex = keyIndex++
191+
const request = store.count(key)
192+
193+
await new Promise(function (resolve, reject) {
194+
request.onsuccess = () => {
195+
results[resultIndex] = request.result === 1
196+
resolve()
197+
}
198+
199+
request.onerror = (ev) => {
200+
ev.stopPropagation()
201+
reject(request.error)
202+
}
203+
})
204+
}
205+
} catch (err) {
206+
abort = true
207+
throw err
208+
}
209+
}
210+
211+
for (let i = 0; i < n; i++) {
212+
bees[i] = bee()
213+
}
214+
215+
await Promise.allSettled(bees)
216+
return results
217+
}
218+
163219
async _del (key, options) {
164220
const store = this[kStore]('readwrite')
165221
const request = store.delete(key)

0 commit comments

Comments
 (0)