From 68b2fb4ed72df8503e165f4b628eb21e13168902 Mon Sep 17 00:00:00 2001 From: Gerold Penz Date: Wed, 31 Jul 2024 15:08:57 +0200 Subject: [PATCH] incr and decr added --- src/index.ts | 16 ++++++++++++++++ tests/memory.test.ts | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/src/index.ts b/src/index.ts index c99f1d6..71bd631 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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(key) ?? 0) + incrBy + if (isNaN(newValue)) return NaN + self.set(key, newValue, ttlMs) + return newValue + })() + } + + + decr(key: string, decrBy: number = 1, ttlMs?: number): number { + return this.incr(key, decrBy * -1, ttlMs) + } + } diff --git a/tests/memory.test.ts b/tests/memory.test.ts index 110df21..de87e37 100644 --- a/tests/memory.test.ts +++ b/tests/memory.test.ts @@ -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(KEY_1, value) + expect(store.incr(KEY_1)).toBeNaN() + expect(store.get(KEY_1)).toEqual(value) + +}) +