Created
October 27, 2016 08:10
-
-
Save alexandrricov/4ebf07f3597a98cdd7ea13a6314e0f68 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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