From df5ff15b40a39f01c6989c0cba0a5145204d9ea4 Mon Sep 17 00:00:00 2001 From: Vitalii Saienko Date: Mon, 2 Sep 2019 13:41:16 +0300 Subject: [PATCH] Support of `key` method --- __tests__/inMemoryStorage.js | 13 +++++++++++++ src/inMemoryStorage.js | 16 ++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/__tests__/inMemoryStorage.js b/__tests__/inMemoryStorage.js index 1bedd39..c228573 100644 --- a/__tests__/inMemoryStorage.js +++ b/__tests__/inMemoryStorage.js @@ -38,6 +38,19 @@ describe('inMemoryStorage', () => { expect(inMemoryStorage.length).toBe(1) }) + test('key', () => { + inMemoryStorage.setItem('key-1', 'value-1') + + expect(() => { + inMemoryStorage.key() + }).toThrow( + "Failed to execute 'key' on 'Storage': 1 argument required, but only 0 present." + ) + + expect(inMemoryStorage.key(0)).toBe('key-1') + expect(inMemoryStorage.key(1)).toBe(null) + }) + test('clear', () => { inMemoryStorage.setItem('key-1', 'value-1') inMemoryStorage.setItem('key-2', 'value-2') diff --git a/src/inMemoryStorage.js b/src/inMemoryStorage.js index 771bce7..03e66cb 100644 --- a/src/inMemoryStorage.js +++ b/src/inMemoryStorage.js @@ -27,6 +27,22 @@ class InMemoryStorage { return null } + key(index) { + if (index === undefined) { + throw new TypeError( + "Failed to execute 'key' on 'Storage': 1 argument required, but only 0 present." + ) + } + + const key = Object.keys(this._data)[index] + + if (key !== undefined) { + return key + } + + return null + } + clear() { this._data = {} this.length = 0