Last active
August 29, 2015 13:56
-
-
Save tastywheat/9003504 to your computer and use it in GitHub Desktop.
object cache syncronization
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
<html> | |
<body> | |
<script> | |
var cacheService = function(){ | |
var cache = {}; | |
function get(key){ | |
return cache[key]; | |
} | |
function getList(keys){ | |
var list = keys.map(function(key){ | |
return cache[key]; | |
}); | |
return list; | |
} | |
function merge(source){ | |
if(!cache[source.id]) | |
cache[source.id] = {}; | |
for(var index in source) | |
cache[source.id][index] = source[index]; | |
} | |
return { | |
get: get, | |
getList: getList, | |
merge: merge | |
} | |
}(); | |
var a = { id: 'a', a: 1 }; | |
var b = { id: 'b', b: 2 }; | |
var c = { id: 'c', b: 3, c: 4 }; | |
cacheService.merge(a); | |
cacheService.merge(b); | |
cacheService.merge(c); | |
var resultB1 = cacheService.get('b'); | |
var resultB2 = cacheService.get('b'); | |
resultB1.b = 4; | |
console.log(resultB1.b); | |
console.log(resultB2.b); | |
var d = { id: 'b', b: 6 }; | |
cacheService.merge(d); | |
var resultB3 = cacheService.get('b'); | |
console.log(resultB3.b); | |
console.log(resultB1.b); | |
console.log(resultB2.b); | |
var items = cacheService.getList(['a','b']); | |
console.log(items); | |
/* | |
output | |
4 | |
4 | |
6 | |
6 | |
6 | |
*/ | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment