Skip to content

Instantly share code, notes, and snippets.

@alexandrricov
Created October 27, 2016 08:10
Show Gist options
  • Save alexandrricov/4ebf07f3597a98cdd7ea13a6314e0f68 to your computer and use it in GitHub Desktop.
Save alexandrricov/4ebf07f3597a98cdd7ea13a6314e0f68 to your computer and use it in GitHub Desktop.
import isClient from 'helpers/isClientSideRender';
function isObject(val) {
return Object.prototype.toString.call(val) === '[object Object]';
}
function fn(dest, obj, rootPath, myColl) {
return Object.keys(obj).reduce(
(acc, key) => {
const val = obj[key];
const path = rootPath ? `${rootPath}.${key}` : key;
if (isObject(val)) {
acc[key] = {};
fn(acc[key], val, path, myColl);
} else {
Object.defineProperty(acc, key, {
get: () => {
myColl.set(path, val);
return val;
},
set: (newVal) => {
console.log('SET:', path, newVal);
}
});
}
return acc;
},
dest
);
}
function addNewItemsToHashMap(parsedItems, key, value) {
key.split('.').reduce(
(acc, field, idx, arr) => {
if (arr.length === idx + 1) {
acc[field] = value;
return acc;
}
if (!isObject(acc[field])) {
acc[field] = {};
}
return acc[field];
},
parsedItems
);
}
function setObservable(name, hashMap) {
if (isClient) {
const myColl = new Map();
const hashMapCollectionKey = `${name}-observable`;
setInterval(
() => {
const storedItems = localStorage.getItem(hashMapCollectionKey);
const parsedItems = JSON.parse(storedItems) || {};
for (const [key, value] of myColl.entries()) {
addNewItemsToHashMap(parsedItems, key, value);
}
localStorage.setItem(hashMapCollectionKey, JSON.stringify(parsedItems));
}, 2000
);
return fn({}, hashMap, '', myColl);
}
return hashMap;
}
export default setObservable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment