Skip to content

Instantly share code, notes, and snippets.

@adoc
Created October 1, 2015 02:29
Show Gist options
  • Save adoc/b403e729d29f5bf86670 to your computer and use it in GitHub Desktop.
Save adoc/b403e729d29f5bf86670 to your computer and use it in GitHub Desktop.
JS code: ns coerce and "gen" check
ns: {
coerce: function (namespace, hash, back) {
hash = hash || {};
back = back || false;
var nsSplit = namespace.split('.'),
newHash = hash,
stop = nsSplit.length - (back && 1 || 0),
ns;
if (_.isEmpty(namespace)) {
return newHash
}
for (var nsi = 0; nsi < stop; nsi++) {
ns = nsSplit[nsi];
newHash = newHash[ns];
if (!newHash) {
return;
}
}
return newHash;
},
// todo: older func check validity.
gen: function (namespace, last, first) {
var nsSplit = namespace.split('.'),
newHash = first || {},
outputHash = newHash,
ns;
last = last || {};
for (var nsi = 0; nsi < nsSplit.length; nsi++) {
ns = nsSplit[nsi];
if (nsi === nsSplit.length - 1) {
newHash[ns] = last;
} else {
newHash[ns] = {};
}
newHash = newHash[ns];
}
return outputHash;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment