Skip to content

Commit

Permalink
incr and decr added
Browse files Browse the repository at this point in the history
  • Loading branch information
gerold-penz committed Jul 31, 2024
1 parent d882574 commit 68b2fb4
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -471,4 +471,20 @@ export class BunSqliteKeyValue {
})
}


incr(key: string, incrBy: number = 1, ttlMs?: number): number {
const self = this
return this.db.transaction(() => {
const newValue = Number(self.get<number>(key) ?? 0) + incrBy
if (isNaN(newValue)) return NaN
self.set<number>(key, newValue, ttlMs)
return newValue
})()
}


decr(key: string, decrBy: number = 1, ttlMs?: number): number {
return this.incr(key, decrBy * -1, ttlMs)
}

}
37 changes: 37 additions & 0 deletions tests/memory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,3 +434,40 @@ test("Proxy-Object (data, d): set, get and delete values", () => {
expect(store.d.myKey2).toBeUndefined()
})


test("incr/decr", async () => {
const store = new BunSqliteKeyValue()

// incr/decr
const resultArray = [
store.incr(KEY_1), store.incr(KEY_1),
store.decr(KEY_1), store.decr(KEY_1),
]
expect(resultArray).toEqual([1, 2, 1, 0])
store.delete(KEY_1)

// ttlMs
store.incr(KEY_1, 1, 30)
await Bun.sleep(40)
expect(store.incr(KEY_1, 1)).toEqual(1)
store.delete(KEY_1)

// incrBy/decrBy
store.incr(KEY_1, 2)
expect(store.incr(KEY_1, 2)).toEqual(4)
expect(store.incr(KEY_1, -2)).toEqual(2)
expect(store.decr(KEY_1, 1)).toEqual(1)
expect(store.decr(KEY_1, -1)).toEqual(2)

// String with number
store.set(KEY_1, "100")
expect(store.incr(KEY_1)).toEqual(101)

// NaN
const value: string = "I am no number"
store.set<string>(KEY_1, value)
expect(store.incr(KEY_1)).toBeNaN()
expect(store.get<string>(KEY_1)).toEqual(value)

})

0 comments on commit 68b2fb4

Please sign in to comment.