Skip to content

Implement has() and hasMany() #25

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 20, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 57 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,9 @@ class BrowserLevel extends AbstractLevel {
snapshots: false,
createIfMissing: false,
errorIfExists: false,
seek: true
seek: true,
has: true,
getSync: false
}, forward)

if (typeof location !== 'string' || location === '') {
Expand Down Expand Up @@ -160,6 +162,60 @@ class BrowserLevel extends AbstractLevel {
return values
}

async _has (key, options) {
const store = this[kStore]('readonly')
const request = store.count(key)
const count = await this[kOnComplete](request)

return count === 1
}

async _hasMany (keys, options) {
const store = this[kStore]('readonly')
const iterator = keys.values()

// Consume the iterator with N parallel worker bees
const n = Math.min(16, keys.length)
const bees = new Array(n)
const results = new Array(keys.length)

let keyIndex = 0
let abort = false

const bee = async function () {
try {
for (const key of iterator) {
if (abort) break

const resultIndex = keyIndex++
const request = store.count(key)

await new Promise(function (resolve, reject) {
request.onsuccess = () => {
results[resultIndex] = request.result === 1
resolve()
}

request.onerror = (ev) => {
ev.stopPropagation()
reject(request.error)
}
})
}
} catch (err) {
abort = true
throw err
}
}

for (let i = 0; i < n; i++) {
bees[i] = bee()
}

await Promise.allSettled(bees)
return results
}

async _del (key, options) {
const store = this[kStore]('readwrite')
const request = store.delete(key)
Expand Down