Created
January 5, 2017 09:41
-
-
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.
This file contains hidden or 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
/** | |
* @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