-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathkv.js
3049 lines (2687 loc) · 109 KB
/
kv.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use strict';
const {minimatch} = require('minimatch');
const XMap = require('./XMap.js');
// The cleanup loop runs as long as there's at least one key set, and will
// regularly check for expired keys and remove them from the store.
const CLEANUP_INTERVAL = 20;
class kvjs {
constructor() {
// Initialize the store and expireTimes maps
this.store = new XMap();
this.expireTimes = new XMap();
// wrap the set function to trigger the cleanup interval on each set
this.storeSet = (key, value) => {
this.store.set(key, value);
this._initCleanupLoop(CLEANUP_INTERVAL);
}
}
/**
* Set the string value of a key with optional NX/XX/GET/EX/PX/EXAT/PXAT/KEEPTTL, GET, and expiration options.
* @param {*} key - The key to set.
* @param {*} value - The value to set.
* @param {Object} [options] - An object with optional arguments.
* NX (boolean): Set the key only if it does not exist.
* XX (boolean): Set the key only if it already exists.
* GET (boolean): Return the old value of the key before setting the new value.
* EX (number|undefined): Set the key with an expiration time (in seconds).
* PX (number|undefined): Set the key with an expiration time (in milliseconds).
* EXAT (number|undefined): Set the key with an exact UNIX timestamp (in seconds) for expiration.
* PXAT (number|undefined): Set the key with an exact UNIX timestamp (in milliseconds) for expiration.
* KEEPTTL (boolean): Retain the key's existing TTL when setting a new value.
* @returns {boolean|undefined} - true if the operation was successful, or the existing value if the GET option is specified and the key already exists.
*/
set(key, value, options = {}) {
const {
NX = false,
XX = false,
GET = false,
EX = undefined,
PX = undefined,
EXAT = undefined,
PXAT = undefined,
KEEPTTL = false,
} = options;
const nx = NX;
const xx = XX;
const get = GET;
let ex = EX ? parseInt(EX, 10) : undefined;
let px = PX ? parseInt(PX, 10) : undefined;
let exat = EXAT ? parseInt(EXAT, 10) : undefined;
let pxat = PXAT ? parseInt(PXAT, 10) : undefined;
const keepttl = KEEPTTL;
// Check if the key already exists
const exists = this.store.has(key);
if (xx && !exists) {
return undefined;
}
if (nx && exists) {
return undefined;
}
// Get the existing value if the GET option is specified
let oldValue;
if (get && exists) {
oldValue = this.store.get(key);
}
// Set the new value
this.storeSet(key, value);
// Handle expiration options
if (ex !== undefined || px !== undefined || exat !== undefined || pxat !== undefined || keepttl) {
let expireTime = undefined;
if (ex !== undefined) {
expireTime = Date.now() + ex * 1000;
} else if (px !== undefined) {
expireTime = Date.now() + px;
} else if (exat !== undefined) {
expireTime = exat * 1000;
} else if (pxat !== undefined) {
expireTime = pxat;
} else if (keepttl && exists) {
expireTime = this.expireTimes.get(key);
}
if (expireTime !== undefined) {
this.expireTimes.set(key, expireTime);
}
} else {
this.expireTimes.delete(key);
}
return get ? oldValue : true;
}
/**
* Get the value of a key.
* @param {*} key - The key to get.
* @returns {*} - The value of the key, or `undefined` if the key does not exist or has expired.
*/
get(key) {
const isExpired = this._checkAndRemoveExpiredKey(key);
if (isExpired)
return undefined;
return this.store.get(key);
}
/**
* Delete specified key(s). If a key does not exist, it is ignored.
* @param {*} key - The key to delete.
* @returns {number} - 1 if the key was deleted, 0 if the key did not exist or has expired.
*/
del(...keys) {
let numDeleted = 0;
for (const key of keys) {
// Check if the key has expired and remove it if it has.
const isExpired = this._checkAndRemoveExpiredKey(key);
if (isExpired) {
continue;
}
// Delete the key from the Map and delete any existing expiration time.
if (this.store.delete(key)) {
this.expireTimes.delete(key);
numDeleted++;
}
}
// Return the number of keys that were deleted.
return numDeleted;
}
/**
* Check if one or more keys exist.
* @param {...string} keys - The keys to check.
* @returns {number} - The number of keys that exist.
*/
exists(...keys) {
let numExists = 0;
for (const key of keys) {
// Check if the key has expired and remove it if it has.
const isExpired = this._checkAndRemoveExpiredKey(key);
if (isExpired) {
continue;
}
// Increment the number of existing keys if the key exists in the Map.
if (this.store.has(key)) {
numExists++;
}
}
// Return the number of keys that exist.
return numExists;
}
/**
* Increment the value of a key by 1.
* @param {*} key - The key to increment.
* @returns {number} - The new value of the key.
*/
incr(key) {
return this.incrby(key, 1);
}
/**
* Increment the value of a key by a given amount.
* @param {*} key - The key to increment.
* @param {number} increment - The amount to increment the key by.
* @returns {number} - The new value of the key.
* @throws {Error} - If the value of the key is not an integer.
*/
incrby(key, increment) {
let value = this.store.get(key);
if (value === undefined) {
value = 0;
} else if (!Number.isInteger(Number(value))) {
throw new Error('ERR value is not an integer');
}
const newValue = Number(value) + increment;
this.storeSet(key, newValue.toString());
return newValue;
}
/**
* Decrement the value of a key by 1.
* @param {*} key - The key to decrement.
* @returns {number} - The new value of the key.
* @throws {Error} - If the value is not an integer.
*/
decr(key) {
try {
return this.decrby(key, 1);
} catch (err) {
throw err;
}
}
/**
* Decrement the value of a key by a given amount.
* @param {*} key - The key to decrement.
* @param {number} decrement - The amount to decrement the key by.
* @returns {number} - The new value of the key.
* @throws {Error} - If the value is not an integer.
*/
decrby(key, decrement) {
let value = this.store.get(key);
if (value === undefined) {
value = 0;
} else if (!Number.isInteger(Number(value))) {
throw new Error('ERR value is not an integer');
}
const newValue = Number(value) - decrement;
this.storeSet(key, newValue.toString());
return newValue;
}
/**
* Set a key's time to live in seconds.
* @param {*} key - The key to set the expiry time for.
* @param {number} seconds - The number of seconds until the key should expire.
* @param {Object} options - (Optional) An object containing the option for the expiry behavior.
* Can be { NX: true } (set expire only if key has no expiry time),
* { XX: true } (set expire only if key has an expiry time),
* { GT: true } (set expire only if key's expiry time is greater than the specified time),
* or { LT: true } (set expire only if key's expiry time is less than the specified time).
* @returns {number} - 1 if the key's expiry time was set, 0 otherwise.
*/
expire(key, seconds, options = {}) {
if (!this.store.has(key)) {
return 0;
}
const { NX = false, XX = false, GT = false, LT = false } = options;
const now = Date.now();
const expireTime = this.expireTimes.get(key);
if (NX && expireTime !== undefined) {
return 0;
} else if (XX && expireTime === undefined) {
return 0;
} else if (GT && (expireTime === undefined || expireTime <= now + seconds * 1000)) {
return 0;
} else if (LT && (expireTime === undefined || expireTime >= now + seconds * 1000)) {
return 0;
}
this.expireTimes.set(key, now + seconds * 1000);
return 1;
}
/**
* Find all keys matching the specified pattern.
* @param {string} pattern - The pattern to match keys against. Supports glob-style patterns.
* @returns {Array} - An array of keys that match the specified pattern.
*/
keys(pattern) {
const keys = [];
for (const [key, value] of this.store.entries()) {
if (minimatch(key, pattern, { nocase: true })) {
const expireTime = this.expireTimes.get(key);
if (expireTime === undefined || expireTime > Date.now()) {
keys.push(key);
}
}
}
return keys;
}
/**
* Returns an array of values stored at the given keys. If a key is not found, undefined is returned for that key.
* @param {...string} keys - The keys to retrieve.
* @returns {Array} - An array of values.
*/
mget(...keys) {
return keys.map(key => this.get(key));
}
/**
* Set multiple keys to their respective values.
* @param {...any} keyValuePairs - The keys and values to set, given as alternating arguments.
* @returns {boolean} - A boolean indicating that the operation was successful.
* @throws {Error} - If the number of arguments is odd.
*/
mset(...keyValuePairs) {
if (keyValuePairs.length % 2 !== 0) {
throw new Error('MSET requires an even number of arguments');
}
for (let i = 0; i < keyValuePairs.length; i += 2) {
this.set(keyValuePairs[i], keyValuePairs[i + 1]);
}
return true;
}
/**
* Renames a key to a new key only if the new key does not exist.
* @param {string} oldKey - The old key name.
* @param {string} newKey - The new key name.
* @returns {number} - 1 if the key was successfully renamed, 0 otherwise.
*/
renamenx(oldKey, newKey) {
if (!this.store.has(oldKey) || this.store.has(newKey)) {
return 0;
}
const value = this.store.get(oldKey);
this.store.delete(oldKey);
this.storeSet(newKey, value);
// Update expiration times if necessary
if (this.expireTimes.has(oldKey)) {
const expireTime = this.expireTimes.get(oldKey);
this.expireTimes.delete(oldKey);
this.expireTimes.set(newKey, expireTime);
}
return 1;
}
/**
* Return a random key from the cache.
* @returns {(string|undefined)} - A random key from the cache or undefined if the cache is empty.
*/
randomkey() {
const keys = Array.from(this.store.keys());
if (keys.length === 0)
return undefined;
const randomIndex = Math.floor(Math.random() * keys.length);
return keys[randomIndex];
}
/**
* Set a key's time-to-live in seconds.
* @param {*} key - The key to set the TTL for.
* @param {number} timestampSeconds - The UNIX timestamp (in seconds) at which the key should expire.
* @param {Object} [options] - An object with optional arguments specifying when the expiration should be set:
* - { NX: true } if the key does not have an expiration time
* - { XX: true } if the key already has an expiration time
* - { GT: true } if the expiration should only be set if it is greater than the current TTL
* - { LT: true } if the expiration should only be set if it is less than the current TTL
* @returns {number} - 1 if the TTL was set, 0 if the key does not exist or the TTL was not set.
* @throws {Error} - Throws an error if the timestampSeconds parameter is not a valid number.
*/
expireat(key, timestampSeconds, options = {}) {
if (typeof timestampSeconds !== 'number' || isNaN(timestampSeconds)) {
throw new Error('ERR invalid expire time in SETEX');
}
// If the key does not exist, return 0
if (!this.store.has(key)) {
return 0;
}
const { NX = false, XX = false, GT = false, LT = false } = options;
const now = Date.now();
const ttlMillis = (timestampSeconds * 1000) - now;
if (ttlMillis <= 0) {
this.store.delete(key);
this.expireTimes.delete(key);
return 0;
}
const existingTtl = this.pttl(key);
if (XX && existingTtl === -1) {
// Do nothing, key does not exist or has no TTL
return 0;
} else if (NX && existingTtl !== -1) {
// Do nothing, key exists and has a TTL set
return 0;
} else if (GT && (existingTtl !== -1 && ttlMillis <= existingTtl)) {
// Do nothing, key exists and new TTL is less than or equal to existing TTL
return 0;
} else if (LT && (existingTtl !== -1 && ttlMillis >= existingTtl)) {
// Do nothing, key exists and new TTL is greater than or equal to existing TTL
return 0;
}
return this.pexpire(key, ttlMillis);
}
/**
* Set a timeout for the key, in milliseconds.
* @param {*} key - The key to set the expiration for.
* @param {number} ttlMillis - The time-to-live for the key, in milliseconds.
* @param {Object} [options] - An object with optional arguments specifying when the expiration should be set:
* - { NX: true } if the key does not have an expiration time
* - { XX: true } if the key already has an expiration time
* - { GT: true } if the expiration should only be set if it is greater than the current TTL
* - { LT: true } if the expiration should only be set if it is less than the current TTL
* @returns {number} - 1 if the timeout was set, 0 otherwise.
*/
pexpire(key, ttlMillis, options = {}) {
const { NX = false, XX = false, GT = false, LT = false } = options;
if (NX && this.store.has(key) || XX && !this.store.has(key)) {
return 0;
}
if (GT || LT) {
const existingTTL = this.pttl(key);
if (GT && existingTTL >= ttlMillis || LT && existingTTL <= ttlMillis) {
return 0;
}
}
this.expireTimes.set(key, Date.now() + ttlMillis);
return 1;
}
/**
* Sets the expiration timestamp for the key in milliseconds.
* @param {*} key - The key to set the expiration timestamp for.
* @param {number} timestampMillis - The expiration timestamp in milliseconds.
* @returns {number} - 1 if the timeout was set, 0 if the key does not exist or the timeout could not be set.
*/
pexpireat(key, timestampMillis) {
const ttlMillis = timestampMillis - Date.now();
if (ttlMillis <= 0) {
this.store.delete(key);
this.expireTimes.delete(key);
return 0;
}
return this.pexpire(key, ttlMillis);
}
/**
* Returns the remaining time to live of a key that has an expiration set, in milliseconds.
* If the key does not exist or does not have an associated expiration time, it returns -2 or -1, respectively.
*
* @param {*} key - The key to check.
* @returns {number} - The remaining time to live in milliseconds. If the key does not exist or has no expiration, returns -2 or -1 respectively.
*/
pttl(key) {
if (!this.store.has(key)) {
return -2;
}
if (!this.expireTimes.has(key)) {
return -1;
}
const ttl = this.expireTimes.get(key) - Date.now();
return ttl > 0 ? ttl : -2;
}
/**
* Returns the time-to-live of a key in seconds. If the key does not exist or does not have an
* associated expiration time, it returns -2 or -1, respectively. If the key exists and has an
* associated expiration time, it returns the number of seconds left until expiration. The returned
* value can be negative if the key has already expired.
*
* @param {*} key - The key to check the time-to-live for.
* @returns {number} - The time-to-live of the key in seconds, or -2 if the key does not exist,
* -1 if the key exists but does not have an associated expiration time, or a negative value if
* the key has already expired.
*/
ttl(key) {
if (!this.store.has(key)) {
return -2;
}
if (!this.expireTimes.has(key)) {
return -1;
}
const ttl = Math.floor((this.expireTimes.get(key) - Date.now()) / 1000);
return ttl > 0 ? ttl : -2;
}
/**
* Remove the expiration from a key.
* @param {*} key - The key to remove expiration from.
* @returns {number} - 1 if the expiration was removed, 0 otherwise.
*/
persist(key) {
if (!this.store.has(key) || !this.expireTimes.has(key)) {
return 0;
}
this.expireTimes.delete(key);
return 1;
}
/**
* Get a substring of the string stored at a key.
* @param {*} key - The key to get the substring from.
* @param {number} start - The starting index of the substring (0-based).
* @param {number} end - The ending index of the substring (0-based, inclusive).
* @returns {string} - The substring, or an empty string if the key does not exist or is not a string.
*/
getrange(key, start, end) {
const value = this.get(key);
if (typeof value !== 'string')
return '';
return value.slice(start, end + 1);
}
/**
* Replaces the current value of a key with the specified new value and returns the old value.
* If the key does not exist, it is created and set to the specified value.
* @param {*} key - The key to update.
* @param {*} value - The new value to set.
* @returns {string|undefined} - The old value of the key, or undefined if the key did not exist.
*/
getset(key, value) {
const oldValue = this.get(key);
this.set(key, value);
return oldValue;
}
/**
* Set the value of a key with an expiration time in milliseconds.
* If the key already exists, it will be overwritten with the new value.
* @param {*} key - The key to set.
* @param {*} value - The value to set for the key.
* @param {number} ttl - The time-to-live for the key, in milliseconds.
* @returns {boolean|undefined} - true if the key was set successfully.
*/
setex(key, value, ttl) {
if (!this.store.has(key))
return undefined;
this.set(key, value);
this.expire(key, ttl);
return true;
}
/**
* Sets the substring of the string value stored at the specified key starting at the specified offset
* with the given value. If the offset is out of range, will return an error.
* If the key does not exist, a new key holding a zero-length string will be created.
* The length of the string will be increased as necessary to accommodate the new value.
* @param {*} key - The key of the string value to set the range of.
* @param {number} offset - The zero-based index at which to start replacing characters.
* @param {*} value - The new value to insert into the string.
* @returns {number} - The length of the string after it has been modified.
* @throws {Error} - If the offset is out of range or an error occurs while executing the command.
*/
setrange(key, offset, value) {
if (typeof offset !== 'number' || offset < 0) {
throw new Error('Invalid offset value');
}
if (typeof value !== 'string') {
throw new Error('Value must be a string');
}
let currentValue = this.get(key);
if (currentValue === undefined || currentValue === undefined) {
currentValue = '';
}
const left = currentValue.slice(0, offset);
const right = currentValue.slice(offset + value.length);
const newValue = left + value + right;
this.set(key, newValue);
return newValue.length;
}
/**
* Get the length of the value stored at a key.
* @param {*} key - The key to get the length of.
* @returns {number} - The length of the value stored at the key, or 0 if the key does not exist.
*/
strlen(key) {
const value = this.get(key);
return value === undefined ? 0 : value.length;
}
/**
* Set the values of multiple keys.
* @param {*} keyValuePairs - The key-value pairs to set.
* @param {*} value - The value to set for the key.
* @returns {number} - 1 if the key was set, 0 if the key was not set.
* @throws {Error} - If an error occurs while executing the command.
*/
msetnx(...keyValuePairs) {
if (keyValuePairs.length % 2 !== 0) {
throw new Error('MSETNX requires an even number of arguments');
}
for (let i = 0; i < keyValuePairs.length; i += 2) {
if (this.store.has(keyValuePairs[i])) {
return 0;
}
}
for (let i = 0; i < keyValuePairs.length; i += 2) {
this.set(keyValuePairs[i], keyValuePairs[i + 1]);
}
return 1;
}
/**
* Increment the value of a key by a floating-point number.
* @param {*} key - The key to increment.
* @param {number} increment - The value to increment by.
* @returns {number} - The new value of the key.
* @throws {Error} - If the value is not a valid float.
*/
incrbyfloat(key, increment) {
let value = this.store.get(key);
if (value === undefined) {
value = 0;
} else if (isNaN(parseFloat(value))) {
throw new Error('ERR value is not a valid float');
}
const newValue = parseFloat(value) + increment;
this.storeSet(key, newValue.toString());
return newValue;
}
/**
* If the key already exists, the value is appended to the end of the existing value.
* If the key doesn't exist, a new key is created and set to the value.
* @param {*} key - The key to append the value to.
* @param {*} value - The value to append.
* @returns {number} - The length of the new string.
*/
append(key, value) {
const currentValue = this.get(key);
const newValue = currentValue === undefined ? value : currentValue + value;
this.set(key, newValue);
return newValue.length;
}
/**
* Returns the bit value at a given offset in the string value of a key.
* @param {*} key - The key to get the bit from.
* @param {number} offset - The bit offset.
* @returns {number} - 1 or 0, the bit value at the given offset. If the key does not exist or the offset is out of range, 0 is returned.
*/
getbit(key, offset) {
const value = this.get(key);
if (value === undefined || offset >= value.length * 8) {
return 0;
}
const byteIndex = Math.floor(offset / 8);
const bitIndex = 7 - (offset % 8);
const byteValue = value.charCodeAt(byteIndex);
return (byteValue >> bitIndex) & 1;
}
/**
* Sets or clears the bit at offset in the string value stored at key.
* @param {*} key - The key to set the bit on.
* @param {number} offset - The bit offset.
* @param {number} bit - The bit value to set.
* @returns {number} - The original bit value stored at offset.
*/
setbit(key, offset, bit) {
if (bit !== 0 && bit !== 1) {
throw new Error('ERR bit is not an integer or out of range');
}
let value = this.get(key);
if (value === undefined) {
value = '';
}
const byteIndex = Math.floor(offset / 8);
const bitIndex = 7 - (offset % 8);
while (byteIndex >= value.length) {
value += '\x00';
}
const byteValue = value.charCodeAt(byteIndex);
const oldValue = (byteValue >> bitIndex) & 1;
const newValue = byteValue & ~(1 << bitIndex) | (bit << bitIndex);
const newStrValue = String.fromCharCode(newValue);
const left = value.slice(0, byteIndex);
const right = value.slice(byteIndex + 1);
const updatedValue = left + newStrValue + right;
this.set(key, updatedValue);
return oldValue;
}
/**
* Copies the value stored at a key to another key.
* @param {*} source - The key to copy from.
* @param {*} destination - The key to copy to.
* @returns {number} - 1 if the key was copied, 0 if the key was not copied.
*/
copy(source, destination) {
const value = this.get(source);
if (value === undefined) {
return 0;
}
this.set(destination, value);
return 1;
}
/**
* Renames a key.
* @param {*} key - The key to rename.
* @param {*} newKey - The new key name.
* @returns {boolean} - true if the key was renamed, an error if the key was not renamed.
*/
rename(key, newKey) {
if (!this.store.has(key)) {
throw new Error('ERR no such key');
}
if (key === newKey) {
return true;
}
const value = this.store.get(key);
const expireTime = this.expireTimes.get(key);
this.storeSet(newKey, value);
this.store.delete(key);
if (expireTime !== undefined) {
this.expireTimes.set(newKey, expireTime);
this.expireTimes.delete(key);
}
return true;
}
/**
* Returns the type of the value stored at a key.
* @param {*} key - The key to get the type of.
* @returns {string} - The type of the value stored at the key.
*/
type(key) {
if (!this.store.has(key)) {
return 'none';
}
const value = this.store.get(key);
return typeof value;
}
/**
* Add members to a set stored at key.
* @param {*} key - The key to add the members to.
* @param {*} members - The members to add to the set.
* @returns {number} - The number of members that were added to the set, not including all the members that were already present in the set.
*/
sadd(key, ...members) {
if (!this.store.has(key)) {
this.storeSet(key, new Set());
}
const set = this.store.get(key);
if (!(set instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
let addedCount = 0;
for (const member of members) {
if (!set.has(member)) {
set.add(member);
addedCount++;
}
}
return addedCount;
}
/**
* Returns the number of members of the set stored at key.
* @param {*} key - The key to get the size of.
* @returns {number} - The number of members in the set.
*/
scard(key) {
const value = this.store.get(key);
if (value === undefined) {
return 0;
}
if (!(value instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
return value.size;
}
/**
* This method retrieves the members of a set that are present in the first set but not in any of the subsequent sets, and returns them as a new set.
* @param {*} key1 - The first key to compare.
* @param {*} otherKeys - The other keys to compare.
* @returns {Array} - An array of members.
*/
sdiff(key1, ...otherKeys) {
const set1 = this.store.get(key1) || new Set();
if (!(set1 instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
const resultSet = new Set(set1);
for (const key of otherKeys) {
const otherSet = this.store.get(key) || new Set();
if (!(otherSet instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
for (const member of otherSet) {
resultSet.delete(member);
}
}
return Array.from(resultSet);
}
/**
* The functionality of this method is similar to that of sdiff, except that instead of returning the resulting set, it stores the set in the destination provided as an argument.
* @param {*} destination - The key to store the resulting set in.
* @param {*} key1 - The first key to compare.
* @param {*} otherKeys - The other keys to compare.
* @returns {number} - The number of elements in the resulting set.
*/
sdiffstore(destination, key1, ...otherKeys) {
const diff = this.sdiff(key1, ...otherKeys);
const resultSet = new Set(diff);
this.storeSet(destination, resultSet);
return resultSet.size;
}
/**
* This method retrieves the members that are present in all the sets provided as arguments, and returns them as a new set representing the intersection of those sets.
* @param {*} keys - The keys to intersect.
* @returns {Array} - An array of members.
*/
sinter(...keys) {
if (keys.length === 0) {
return [];
}
const sets = keys.map(key => {
const set = this.store.get(key);
if (set === undefined) {
return new Set();
}
if (!(set instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
return set;
});
const resultSet = new Set(sets[0]);
for (let i = 1; i < sets.length; i++) {
for (const member of resultSet) {
if (!sets[i].has(member)) {
resultSet.delete(member);
}
}
}
return Array.from(resultSet);
}
/**
* Returns the number of elements in the intersection of one or more sets.
* @param {...string} keys - The keys of the sets to intersect.
* @returns {number} - The cardinality (number of elements) in the intersection of the sets.
*/
sintercard(...keys) {
return this.sinter(...keys).length;
}
/**
* Computes the intersection of one or more sets and stores the result in a new set.
* @param {string} destination - The key of the new set to store the result in.
* @param {...string} keys - The keys of the sets to intersect.
* @returns {number} - The cardinality (number of elements) in the intersection of the sets.
*/
sinterstore(destination, ...keys) {
const intersection = this.sinter(...keys);
const resultSet = new Set(intersection);
this.storeSet(destination, resultSet);
return resultSet.size;
}
/**
* This method determines if a given value is a member of the set stored at key.
* @param {*} key - The key to check.
* @param {*} member - The member to check for.
* @returns {number} - 1 if the member is a member of the set stored at key. 0 if the member is not a member of the set, or if key does not exist.
*/
sismember(key, member) {
const set = this.store.get(key);
if (set === undefined) {
return false;
}
if (!(set instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
return set.has(member) ? true : false;
}
/**
* This method retrieves all the members of the set value stored at key.
* @param {*} key - The key to get the members of.
* @returns {Array} - An array of members.
*/
smembers(key) {
const set = this.store.get(key);
if (set === undefined) {
return [];
}
if (!(set instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
return Array.from(set);
}
/**
* Determines whether each member is a member of the set stored at key.
* @param {*} key - The key to check.
* @param {*} members - The members to check for.
* @returns {Array} - An array of 1s and 0s.
*/
smismember(key, ...members) {
const set = this.store.get(key) || new Set();
if (!(set instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
return members.map(member => (set.has(member) ? 1 : 0));
}
/**
* Moves a member from one set to another.
* @param {*} source - The key of the set to move the member from.
* @param {*} destination - The key of the set to move the member to.
* @param {*} member - The member to move.
* @returns {number} - 1 if the member was moved. 0 if the member was not moved.
*/
smove(source, destination, member) {
const srcSet = this.store.get(source);
if (srcSet === undefined || !srcSet.has(member)) {
return 0;
}
if (!(srcSet instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
const destSet = this.store.get(destination) || new Set();
if (!(destSet instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
srcSet.delete(member);
destSet.add(member);
this.storeSet(destination, destSet);
return 1;
}
/**
* Removes and returns one or multiple random members from a set.
* @param {*} key - The key of the set.
* @param {number} [count=1] - The number of random members to return.
* @returns {Array} An array of random members or an empty array if the set is empty or does not exist.
*/
spop(key, count = 1) {
const set = this.store.get(key);
if (set === undefined) {
return [];
}
if (!(set instanceof Set)) {
throw new Error('ERR Operation against a key holding the wrong kind of value');
}
const poppedMembers = [];
for (const member of set) {
if (poppedMembers.length >= count) {
break;
}
poppedMembers.push(member);
set.delete(member);
}
return poppedMembers;
}
/**
* Get one or multiple random members from a set without removing them.
* @param {*} key - The key of the set.
* @param {number} [count=1] - The number of random members to return.
* @returns {Array} An array of random members or an empty array if the set is empty or does not exist.
*/
srandmember(key, count = 1) {
const set = this.store.get(key);
if (set === undefined) {
return [];