Skip to content

Instantly share code, notes, and snippets.

@adrianseeley
Created January 15, 2014 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save adrianseeley/8429356 to your computer and use it in GitHub Desktop.
Save adrianseeley/8429356 to your computer and use it in GitHub Desktop.
Deeptionary (JS) Nested dictionaries are incredibly powerful functional structures for reinforcement networks, but they can be awfully sloppy to use without polluting the flow representation in the call stack, or causing a stack overflow. This implementation uses a while loop for deep reads/writes instead of recursive function calls to mitigate …
function Deeptionary (Key_Path, Load_From_Dump_Object) {
var obj = Load_From_Dump_Object || {};
var ref = function (Read_Write_Path, Write_Function) {
var path_index = 0;
var walk_obj = obj;
switch (Object.keys(arguments).length) {
case 0: // dump
return obj;
case 1: // read
do {
walk_obj = walk_obj[Read_Write_Path[path_index]] || {};
path_index++;
} while (path_index < Read_Write_Path.length);
return walk_obj;
case 2: // write
do {
if (!walk_obj.hasOwnProperty(Read_Write_Path[path_index])) walk_obj[Read_Write_Path[path_index]] = {};
walk_obj = walk_obj[Read_Write_Path[path_index]] || {};
path_index++;
} while (path_index < Read_Write_Path.length - 1);
walk_obj[Read_Write_Path[path_index]] = Write_Function(walk_obj[Read_Write_Path[path_index]]);
return;
}
};
return ref;
};
// create a new deeptionary {instate: {option: {outstate: {score: {tally: val}}}}}
var D = Deeptionary(['in_state', 'option', 'outstate', 'score', 'tally']);
// create a function that will initialize a value to 0 if it didnt exist then increment it
var incr = function (val) { if (val == null) val = 0; val++; return val; };
// increment a deep state 3 times
D(['myinstate', 'myoption', 'myoutstate', 200], incr);
D(['myinstate', 'myoption', 'myoutstate', 200], incr);
D(['myinstate', 'myoption', 'myoutstate', 200], incr);
// read a deep value
console.log(D(['myinstate', 'myoption', 'myoutstate', 200]));
// output: 3
// dump whole deeptionary
console.log(JSON.stringify(D(), null, ' '));
// output: {"myinstate": {"myoption": {"myoutstate": {"200": 3}}}}
@Demeter
Copy link

Demeter commented Jan 19, 2014

I enjoyed your heroku tetris game enormously! Thank you so much! Regards, dataanxiety on tumblr

@adrianseeley
Copy link
Author

Haha you're welcome, wish I still had the source!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment