Total Complexity | 10 |
Complexity/F | 2 |
Lines of Code | 62 |
Function Count | 5 |
Duplicated Lines | 0 |
Ratio | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
1 | /*eslint no-undef: 0*/ |
||
3 | import { get, isString, isUndefined } from 'lodash'; |
||
4 | import { debug } from './log'; |
||
5 | |||
6 | if (isUndefined(STORAGE_PREFIX)) { |
||
|
|||
7 | throw new Error('STORAGE_PREFIX must be set.'); |
||
8 | } |
||
9 | |||
10 | /** |
||
11 | * |
||
12 | * @param {string} key |
||
13 | */ |
||
14 | export function getStorageItem(key) { |
||
15 | const [root, ...rest] = key.split('.'); |
||
16 | const item = localStorage.getItem(buildStorageKey(root)); |
||
17 | const value = isJson(item) ? JSON.parse(item) : item; |
||
18 | return rest.length ? get(value, rest.join('.')) : value; |
||
19 | } |
||
20 | |||
21 | /** |
||
22 | * |
||
23 | * @param {string} key |
||
24 | * @param {*} value |
||
25 | */ |
||
26 | export function setStorageItem(key, value) { |
||
27 | if (!isString(value)) { |
||
28 | value = JSON.stringify(value); |
||
29 | } |
||
30 | localStorage.setItem(buildStorageKey(key), value); |
||
31 | debug('storage item set: %s -> %s', key, value); |
||
32 | } |
||
33 | |||
34 | /** |
||
35 | * |
||
36 | * @param {string} key |
||
37 | */ |
||
38 | export function removeStorageItem(key) { |
||
39 | localStorage.removeItem(buildStorageKey(key)); |
||
40 | debug('storage item removed: %s', key); |
||
41 | } |
||
42 | |||
43 | /** |
||
44 | * |
||
45 | * @param {string} key |
||
46 | * @returns {string} |
||
47 | */ |
||
48 | function buildStorageKey(key) { |
||
49 | return [STORAGE_PREFIX, key].join('.'); |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * |
||
54 | * @param {*} value |
||
55 | * @returns {boolean} |
||
56 | */ |
||
57 | function isJson(value) { |
||
58 | try { |
||
59 | JSON.parse(value); |
||
60 | } catch (e) { |
||
61 | return false; |
||
62 | } |
||
63 | return true; |
||
64 | } |
||
65 |
This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.
To learn more about declaring variables in Javascript, see the MDN.