Keyed DB
A light-weight node library to manage a sorted & indexed collection with pagination support.
All done using Binary Search. Based off my swift code for Queenfisher
Install
npm i github:erlanggaaXzzz/keyed-db
Running Tests
npm test
Functions
db = new KeyedDB<T> (t => t.uniqueNumberKeyProperty, t => t.optionalUniqueIDProperty)
db = new KeyedDB<T> ({
key: t => t.someProperty,
compare: (t1, t2) => someComputation(t1, t2)
}, t => t.optionalUniqueIDProperty)
db.insert (value)
db.upsert (value)
db.insertIfAbsent (value)
db.delete (value)
db.deleteById (value.optionalUniqueIDProperty)
db.updateKey (value, value => value.uniqueKeyProperty = newValue)
db.paginated (someCursor, 20)
Usage
import KeyedDB from '@erlangga/keyed-db'
type Chat = {
timestamp: Date
chatID: string
}
const db = new KeyedDB<Chat>(value => value.timestamp.getTime()*-1, value => value.chatID)
for (let i = 0; i < 1000;i++) {
db.insert (
{
timestamp: new Date( new Date().getTime() - Math.random()*10000 ),
chatID: `person ${i}`
}
)
}
console.log (db.all())
console.log (db.paginated(null, 20))
console.log (db.paginated(null, 20, null, 'before'))
console.log (db.paginated(null, 20, chat => chat.chatID.includes('something')))
const someDate = new Date().getTime()
const cursorPaginated = db.paginated(someDate, 20)
console.log (cursorPaginated)
db.delete (cursorPaginated[0])
db.updateKey(cursorPaginated[1], value => value.timestamp = new Date().getTime())
Time Complexity
db.insert() | O(logN) |
db.delete() | O(logN) |
db.get() | O(1) |
db.updateKey() | O(logN) |