let count = 0;
let count = 0;
localStorage.getItem('count') ? count = parseInt(localStorage.getItem('count')) : 0;
// parseInt потому, что в значении storage всегда хранится строка.
const createPersistCounter = (name) => {
let value = Number(localStorage.getItem(name) || '');
if (Number.isNaN(value)) {
value = 0;
}
const action = (fn) => () => {
fn();
localStorage.setItem(name, value);
};
const inc = action(() => (value += 1));
const dec = action(() => (value -= 1));
const reset = action(() => (value = 0));
return {
get value() {
return value;
},
inc,
dec,
reset
};
};
const counter = createPersistCounter('clicks');
counter.inc(); // localStorage['clicks'] == 1
counter.inc(); // localStorage['clicks'] == 2