Skip to content

Instantly share code, notes, and snippets.

@replete
Created January 5, 2017 09:41
Show Gist options
  • Save replete/9b4838dd703f01b01a2fa696c61a6ded to your computer and use it in GitHub Desktop.
Save replete/9b4838dd703f01b01a2fa696c61a6ded to your computer and use it in GitHub Desktop.
'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