Created
May 2, 2023 15:27
-
-
Save Duologic/d70b916fb7aed0e9183afc8d4f11ba27 to your computer and use it in GitHub Desktop.
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
local query = 'foo : value1,bar : value2\\,value3'; | |
//local query = 'foo,bar : value2\\,value3'; | |
//local query = 'foo : value1,bar'; | |
//local query = 'foo,bar'; | |
//local query = '1, a : b, ab : , aa: bb, a :b'; | |
local split = std.mapWithIndex(function(i, c) { index: i, char: c }, query); | |
std.foldl( | |
function(acc, item) | |
acc | |
+ ( | |
// Look for <space>:<space>, this indicates key:value pair | |
// If this doesn't exists, then the key==value | |
if ( | |
item.char == ' ' | |
&& split[item.index + 1].char == ':' | |
&& split[item.index + 2].char == ' ' | |
) | |
|| ( | |
item.char == ':' | |
&& split[item.index - 1].char == ' ' | |
&& split[item.index + 1].char == ' ' | |
) | |
|| ( | |
item.char == ' ' | |
&& split[item.index - 2].char == ' ' | |
&& split[item.index - 1].char == ':' | |
) | |
then { | |
isKey: false, | |
current_value: '', | |
} | |
// Look for a comma, that isn't escaped with '\\' | |
// If it isn't escaped, then this ends the key:value pair | |
else if | |
( | |
item.char == ',' | |
&& split[item.index - 1].char != '\\' | |
) | |
then { | |
values+: [{ | |
key: std.stripChars(acc.current_key, ' '), | |
value: std.stripChars(acc.current_value, ' '), | |
}], | |
current_key: '', | |
current_value: '', | |
isKey: true, | |
} | |
// If this is the last array item, | |
// then append the last character to key and/or value | |
else if item.index == (std.length(split) - 1) | |
then { | |
values+: [{ | |
key: | |
std.stripChars( | |
acc.current_key | |
+ ( | |
// Only append to key if this isn't a key:value pair | |
if acc.isKey | |
then item.char | |
else '' | |
), | |
' ' | |
), | |
value: std.stripChars(acc.current_value + item.char, ' '), | |
}], | |
} | |
// Append characters to current tracking key/value | |
else if acc.isKey | |
then { | |
current_key+: item.char, | |
current_value+: item.char, | |
} | |
else { | |
current_value+: item.char, | |
} | |
), | |
split, | |
{ isKey: true } | |
).values |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment