Skip to content

Instantly share code, notes, and snippets.

@ywh233
Last active July 10, 2018 22:45
Show Gist options
  • Save ywh233/9464aa81172cd57ec0779e21d771e581 to your computer and use it in GitHub Desktop.
Save ywh233/9464aa81172cd57ec0779e21d771e581 to your computer and use it in GitHub Desktop.
Simple JS function to parse a C enum definition. Helpful for looking up enum key from debug logs without manual counting or whatsoever.
/**
* Simple function to parse a C enum definition. E.g. Given a string like:
* A = 0,
* B,
* C = B,
* D
*
* Returns a map like: {"A": 0, "B": 1, "C": 1, "D": 2}
*
* @param str The enum definition string to parse.
* @returns {!Map<string, number>} Enum key as string, enum value as value.
*/
function parseCEnum(str) {
// Remove all comments then all unnecessary spaces.
str = str.replace(/\/\/.*$/gm, '').replace(/^\s/gm, '');
const enumMap = {};
let valueIndex = 0;
str.split(',').forEach(line => {
if (line.length == 0) {
// Blank line.
return;
}
const lineSplit = line.split('=');
if (lineSplit.length != 1 && lineSplit.length != 2) {
throw new Error('Syntax error: ' + line);
}
const enumKey = lineSplit[0].trim();
if (lineSplit.length == 2) {
// The assignment value could be a previous enum key.
const assignmentValue = lineSplit[1].trim();
valueIndex = isNaN(assignmentValue) ? enumMap[assignmentValue]
: Number(assignmentValue);
}
enumMap[enumKey] = valueIndex;
valueIndex++;
});
return enumMap;
}
/**
*
* @param str Enum definition to be flattened. E.g. "A = 0, B, C = B, D"
* @returns {string} The flattened definition. E.g. "A = 0, B = 1, C = 1, D = 2"
*/
function flattenEnumDef(str) {
const enumMap = parseCEnum(str);
let newDef = '';
for (let k in enumMap) {
newDef += k + ' = ' + enumMap[k] + ',\n';
}
return newDef;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment