Created
June 14, 2015 23:51
-
-
Save ajschlosser/3ad8574652b8175dc8d8 to your computer and use it in GitHub Desktop.
Object encapsulation
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
return { | |
encapsulate: function(o) { | |
function process(prop, key) { | |
var primary = prop[key]; | |
if (!Array.isArray(prop[key])) { | |
for (var i in primary) { | |
if (primary[i] !== null && typeof primary[i] === 'object') { | |
process(primary, i); | |
} else if (typeof primary[i] !== 'function') { | |
var secondary = primary[i]; | |
primary[i] = this.publicize(secondary); | |
} | |
} | |
} | |
prop[key] = this.publicize(primary); | |
} | |
this.traverse(o, process); | |
return o; | |
}, | |
publicize: function(prop) { | |
if (!Array.isArray(prop) && typeof prop !== 'function') { | |
return function access(p) { | |
if (p && prop[p] && typeof prop[p] === 'function') { | |
return prop[p](); | |
} else if (p && !prop[p]) { | |
return { | |
get: function(){}, | |
set: function(){}, | |
add: function(){} | |
}; | |
} else { | |
var accesses = { | |
get: function() { | |
return prop; | |
}, | |
set: function(value){ | |
prop = value; | |
}, | |
type: function() { | |
return typeof prop; | |
} | |
}; | |
switch (typeof prop) { | |
case 'number': | |
$.extend(accesses, { | |
add: function(n) { | |
prop += parseFloat(n); | |
return prop; | |
} | |
}); | |
break; | |
} | |
return accesses; | |
} | |
}; | |
} else { | |
return prop; | |
} | |
}, | |
traverse: function(o, fn) { | |
for (var i in o) { | |
fn.apply(this, [o, i]); | |
if (o[i] !== null && typeof o[i] === 'object' && !Array.isArray(o[i])) { | |
this.traverse(o[i], fn); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment