Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
'Hash' safe property name. Take an object and represent it as a 'safe' javascript property string, for purposes of memoization.
/**
* @param {Object|string} input - The string or object to flatten into a hash key string
* @returns {string} - a string representing the object as a unique string.
* @example hashSafePropertyName({a:200,b:500,c:[300,200,'eggs']}); // 'a$200_b$500_c$__300_200_eggs__'
*/
function hashSafePropertyName(input) {
var isString = _.isString(input);
var isObject = _.isObject(input) && !_.isEmpty(input) && _.isArray(input);
if (!isString && !isObject) {
return false;
}
return (isObject ? JSON.stringify(input) : input)
.replace(/[\"|{|}]/g,'')
.replace(/,/g,'_')
.replace(/:/g,'$')
.replace(/[\[|\]]/g,'__');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.