Skip to content

Instantly share code, notes, and snippets.

@tenbits
Last active December 26, 2015 11:49
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 tenbits/7146008 to your computer and use it in GitHub Desktop.
Save tenbits/7146008 to your computer and use it in GitHub Desktop.
Object normalization - needs to be improved
var obj_normalize = (function() {
function runNormalizer(currentValue, normalizer) {
if (typeof normalizer === 'function')
return normalizer(currentValue);
// other types of normalization, like Regexp-Replace
return currentValue.replace(normalizer[0], normalizer[1]);
// ...
}
function normalizeProperty(obj, path, names, normalizers) {
var value = obj_getProperty(obj, path),
x;
names.forEach(function(name) {
x = runNormalizer(value, normalizers[name]);
if (x !== value)
obj_setProperty(obj, path, x);
value = x;
});
}
return function(obj, properties, normalizers) {
for (var path in properties)
normalizeProperty(obj, path, properties[path], normalizers);
};
}());
function obj_getProperty(obj, property) {
var chain = property.split('.'),
imax = chain.length,
i = 0;
for (; i < imax; i++) {
if (obj == null)
return null;
obj = obj[chain[i]];
}
return obj;
}
function obj_setProperty(obj, property, value) {
var chain = property.split('.'),
imax = chain.length,
i = 0,
key = null;
for (; i < imax - 1; i++) {
key = chain[i];
if (obj[key] == null) {
obj[key] = {};
}
obj = obj[key];
}
obj[chain[i]] = value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment