Last active
December 26, 2015 11:49
-
-
Save tenbits/7146008 to your computer and use it in GitHub Desktop.
Object normalization - needs to be improved
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
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