mirror of
https://github.com/wassname/talk.git
synced 2026-09-12 13:01:11 +08:00
Full PromisifiedStorage + Simplifications
This commit is contained in:
@@ -0,0 +1,34 @@
|
||||
import createInMemoryStorage from "./InMemoryStorage";
|
||||
|
||||
it("should set and unset values", () => {
|
||||
const storage = createInMemoryStorage();
|
||||
storage.setItem("test", "value");
|
||||
expect(storage.getItem("test")).toBe("value");
|
||||
storage.removeItem("test");
|
||||
expect(storage.getItem("test")).toBeNull();
|
||||
});
|
||||
|
||||
it("should return length", () => {
|
||||
const storage = createInMemoryStorage();
|
||||
storage.setItem("a", "value");
|
||||
storage.setItem("b", "value");
|
||||
storage.setItem("c", "value");
|
||||
expect(storage.length).toBe(3);
|
||||
});
|
||||
|
||||
it("should nth key", () => {
|
||||
const storage = createInMemoryStorage();
|
||||
storage.setItem("a", "0");
|
||||
storage.setItem("b", "1");
|
||||
storage.setItem("c", "2");
|
||||
expect(storage.key(2)).toBe("c");
|
||||
});
|
||||
|
||||
it("accepts predefined data", () => {
|
||||
const storage = createInMemoryStorage({
|
||||
a: "0",
|
||||
b: "1",
|
||||
c: "2",
|
||||
});
|
||||
expect(storage.toString()).toMatchSnapshot();
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* InMemoryStorage is a dumb implementation of the Storage interface that will
|
||||
* not persist the data at all. It implements the Storage interface found:
|
||||
*
|
||||
* https://developer.mozilla.org/en-US/docs/Web/API/Storage
|
||||
*/
|
||||
class InMemoryStorage implements Storage {
|
||||
private data: Record<string, string>;
|
||||
|
||||
constructor(data: Record<string, string> = {}) {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
get length() {
|
||||
return Object.keys(this.data).length;
|
||||
}
|
||||
|
||||
public clear() {
|
||||
this.data = {};
|
||||
}
|
||||
|
||||
public key(n: number) {
|
||||
if (this.length <= n) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return Object.keys(this.data)[n];
|
||||
}
|
||||
|
||||
public getItem(key: string) {
|
||||
return this.data[key] || null;
|
||||
}
|
||||
|
||||
public setItem(key: string, value: string) {
|
||||
this.data[key] = value;
|
||||
}
|
||||
|
||||
public removeItem(key: string) {
|
||||
delete this.data[key];
|
||||
}
|
||||
|
||||
public toString() {
|
||||
return JSON.stringify(this.data);
|
||||
}
|
||||
}
|
||||
|
||||
export default function createInMemoryStorage(data?: Record<string, string>) {
|
||||
return new InMemoryStorage(data);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`accepts predefined data 1`] = `"{\\"a\\":\\"0\\",\\"b\\":\\"1\\",\\"c\\":\\"2\\"}"`;
|
||||
@@ -0,0 +1 @@
|
||||
export { default as createInMemoryStorage } from "./InMemoryStorage";
|
||||
Reference in New Issue
Block a user