Last active
March 25, 2022 19:05
-
-
Save LighteningCode/7c89785f185a8fe5652a1048d780e632 to your computer and use it in GitHub Desktop.
Highly performant key=value string parser
This file contains 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
// CommonJS | |
exports.getFlagValues = function (queryCommand = "") { | |
let FlagValuesObject = {}; | |
const stringParts = queryCommand | |
.split(" ") | |
.map((part) => part.replace(/["']/g, "")); | |
let valueCompleted = true; | |
let accummulator_key = ""; | |
let accummulator_value = []; | |
const splitParts = stringParts.map((part) => part.split("=")).filter(part => part[0] !== ""); | |
for (let i = 0; i < splitParts.length; i++) { | |
if (i === 0) { | |
// dont do anything ignore the command part | |
} else { | |
if (splitParts.length - 1 === i) { | |
// we have reached the end | |
if (valueCompleted === false) { | |
accummulator_value.push(splitParts[i][0]) | |
FlagValuesObject[accummulator_key] = accummulator_value.join(" ") | |
} | |
} else { | |
// we have not reached the last item yet | |
// we get to the current item less than 2 | |
if (splitParts[i].length < 2) { | |
valueCompleted = false | |
// check the value before this | |
if (splitParts[i - 1].length > 1) { | |
accummulator_key = splitParts[i - 1][0] | |
accummulator_value.push(splitParts[i - 1][1]) | |
accummulator_value.push(splitParts[i][0]) | |
} else { | |
accummulator_value.push(splitParts[i][0]) | |
} | |
} | |
} | |
if (splitParts[i].length > 1) { | |
if (valueCompleted === true) { | |
FlagValuesObject[splitParts[i][0]] = splitParts[i][1] | |
} else { | |
if (splitParts.length - 1 === i) { | |
// we are done accumulating | |
valueCompleted = true | |
FlagValuesObject[accummulator_key] = accummulator_value.filter((_,idx) => accummulator_value.length - 1 !== idx).join(" ") | |
accummulator_value = accummulator_value.filter(() => false) | |
accummulator_key = "" | |
FlagValuesObject[splitParts[i][0]] = splitParts[i][1] | |
} else { | |
// we are done accumulating | |
valueCompleted = true | |
FlagValuesObject[accummulator_key] = accummulator_value.join(" ") | |
// reset | |
accummulator_value = accummulator_value.filter(() => false) | |
accummulator_key = "" | |
FlagValuesObject[splitParts[i][0]] = splitParts[i][1] | |
} | |
} | |
} else { | |
if (splitParts.length > i && valueCompleted === true) { | |
// get the last but one item | |
let keyBefore = splitParts[i - 1][0] | |
let valueBefore = splitParts[i - 1][1] | |
// add the last but one item | |
FlagValuesObject[keyBefore] = valueBefore.split(" ") + " " + splitParts[i][0] | |
} | |
} | |
} | |
} | |
return FlagValuesObject; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment