【发布时间】:2022-10-13 11:15:07
【问题描述】:
在我的特定领域语言中,我可以使用虚线路径引用树状结构内的某些内容,除了我也可以连续两个点“向上”:
"sibling" // gets sibling
".sibling" // same as above
".sibling.nested" // indexes into sibling with 'nested'
"..down" // goes up the hierarchy, then down the key 'down'
"down.." // doesn't do anything, really, goes down and then back up
".." // references parent
"down..down" // same as "down"
我需要像这样拆分上面的内容:
["sibling"]
["sibling"]
["sibling", "nested"]
[symbol, "down"]
["down", symbol]
[symbol]
["down", symbol, "down"]
本质上,将.. 替换为符号,但通常由单个. 拆分。我可以像这样拆分普通的点状嵌套路径(甚至尊重转义句点):
path.split(/(?<!\\)\./)
键可能包含任何字符,因此单词边界有时不起作用。
但是我很难找到一个可以替代.. 的干净解决方案。我目前的解决方案是用符号替换所有空字符串(空字符串表示一行中有两个句点),并将一个字符附加到路径的末尾,在拆分完成后删除:
const symbol = Symbol();
function split(path) {
path = "$" + path + "$"; // Any character can work; I just used '$' here
// Split by dots, replacing empty strings with the symbol
const split = path.split(/(?<!\\)\./).map((part) => (!part ? symbol : part));
// Remove prefixed character from start
split[0] = split[0].slice(1);
// Remove suffixed character from end
split[split.length - 1] = split[split.length - 1].slice(0, -1);
// Remove start or end if they are empty
if (!split[0]) split.shift();
if (!split[split.length - 1]) split.pop();
// Done
return split;
}
const tests = [
"sibling" , // gets sibling
".sibling" , // same as above
".sibling.nested", // indexes into sibling with 'nested'
"..down" , // goes up the hierarchy, then down the key 'down'
"down.." , // doesn't do anything, really, goes down and then back up
".." , // references parent
"down..down" , // same as "down"
];
// (Stack Overflow snippet console displays null instead of Symbol)
console.log(tests.map(split));
它完成了工作,通过了所有测试用例,但它过于冗长和笨拙。我正在寻找一个比这更短更容易的解决方案。
【问题讨论】:
标签: javascript