Last active
November 22, 2019 00:48
-
-
Save inexorabletash/5613707 to your computer and use it in GitHub Desktop.
How to iterate over a list of keys using a cursor, using IndexedDB.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2019 Google LLC. | |
// SPDX-License-Identifier: Apache-2.0 | |
var name = 'db' + Date.now(); | |
var openReq = indexedDB.open(name, 1); | |
openReq.onupgradeneeded = function() { | |
var db = openReq.result; | |
var store = db.createObjectStore('store'); | |
for (var i = 0; i < 100; i += 10) | |
store.put("record-" + i, i); | |
}; | |
openReq.onsuccess = function() { | |
var db = openReq.result; | |
var tx = db.transaction('store', 'readwrite'); | |
var store = tx.objectStore('store'); | |
var compare = indexedDB.cmp.bind(indexedDB); | |
var keys = [ 25, 35, 45, 30, 40, 50, 50, 25 ]; | |
sort_unique(keys, compare); | |
function emit(k, v) { console.log([k, v]); } | |
var r = store.openCursor(IDBKeyRange.bound(keys[0], keys[keys.length-1])); | |
r.onsuccess = function() { | |
var cursor = r.result; | |
if (cursor) { | |
while(keys.length && indexedDB.cmp(keys[0], cursor.key) <= 0) | |
keys.shift(); | |
emit(cursor.key, cursor.value); | |
if (keys.length) | |
cursor.continue(keys[0]); | |
} | |
}; | |
}; | |
function sort_unique(array, compare) { | |
array.sort(compare); | |
var i = 1; | |
while (i < array.length) { | |
if (compare(array[i], array[i-1]) === 0) { | |
array.splice(i, 1); | |
} else { | |
++i; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment