gpt4 book ai didi

javascript - JS 验证点符号字符串

转载 作者:行者123 更新时间:2023-12-03 00:32:31 25 4
gpt4 key购买 nike

假设我有一个现有的 Items 数组:

const existingItems = [
{
"path": "xxx.yyy.zzz"
},
{
"path": "yyy.xxx.zzz"
}
];

用户将向此数组添加一个新元素 - 例如:

const newItem = {
"path": "yyy.xxx"
};

如何验证 newItem.path 不会与任何绝对路径匹配?

我尝试了几种方法,但每次都落在不同的 if 语句上,这使得代码非常脏。有什么好的神奇功能可以实现以下场景吗?

例如:

场景 1: 当新路径是现有路径的一部分

let current = 'yyy.xxx.zzz'; // current existing Item
let newPath = 'yyy.xxx'; //new

//无效 => 预期为 false

场景 2: 当新路径包含在现有路径的一部分中时

let current = 'yyy.xxx.zzz'; // current existing Item
let newPath = 'yyy.xxx.z'; //new

//有效 => 预期为 true

场景 3: 当新路径包含现有路径时

 let current = 'yyy.xxx.zzz'; // current existing Item
let newPath = 'yyy.xxx.zzz.ggg '; //new

//无效 => 预期为 false

场景 4: 当新路径包含在现有路径的一部分中时

let current = 'yyy.xxx.zzz'; // current existing Item
let newPath = 'yy'; //new

//有效 => 预期为 true

场景 5: 当新路径被多次包含时

let current = 'yyy.xxx.zzz'; // current existing Item
let newPath = 'xxx.yyy.xxx.zzz'; //new

//有效 => 预期为 true

场景 6: 当新路径有一个点

 let current = 'yyy.xxx.zzz'; // current existing Item
let newPath = 'yyy.'; //new

//无效 => 预期为 false

最佳答案

您可以使用.split来获取子路径,然后比较它们:

  const isValid = parts => parts.every(e => e.length);
const matches = (parts, other) => parts.every((part, i) => part === other[i]);

const parts = newItem.path.split(".");
const existing = existingItems.map(item => item.path.split(".");

const result = isValid(parts) && existing.every(e => !matches(parts, e));

关于javascript - JS 验证点符号字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53795789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com