gpt4 book ai didi

javascript - 如何将字符串解析为比较运算符?

转载 作者:行者123 更新时间:2023-11-30 11:18:09 24 4
gpt4 key购买 nike

我实现了一种根据指定选项过滤商品的方法。该方法以包含搜索参数的选项对象作为参数,例如:{name: "item 2", Price: "<= 1000", count: "> 2"},每个选项都是可选的。该方法必须返回带有商品的过滤数组。过滤产品依据(选项)。我设法按名称进行过滤。告诉我如何正确地按数字过滤,以便过滤器调用如下所示:

console.log(shop.filterProductBy({
name: "product 1",
count: ">1",
price: "<=1000"}));

“count”和“price”需要与比较运算符一起解析,比较运算符设置过滤器的范围,这里有一个函数可以做到这一点,我如何在我的方法中实现这个函数,一切会起作用吗?

function parseCompOperator(oString, lhs) {
if (oString.match("(?:<|>)=?\\d+") === null) {
return "Invalid input";
}

let rator = oString.match("(?:<|>)=?")[0];
let rhs = oString.match("\\d+")[0] * 1;

if (rator === '>') {
return (lhs > rhs);
}
else if (rator === '<') {
return (lhs < rhs);
}
else if (rator === '>=') {
return (lhs >= rhs);
}
else if (rator === '<=') {
return (lhs <= rhs);
}
}

所有代码:

//Product Creation Class
class Product {
constructor(name, count, price) {
this.name = name;
this.count = count;
this.price = price;
}
}
//Сlass where products are recorded
class Shop {
constructor(products) {
this.products = [];
}
//method for adding a product
addProduct(newProduct) {
this.products.push(newProduct);
}
//method for filtering products by specified parameters
filterProductBy(options) {
const optionName = options.name,
optionCount = options.count,
optionPrice = options.price;

const filters = {
byName: function (actualName, optionName) {
return (actualName === undefined) || (actualName === optionName);
},

byCount: function (actualCount, optionCount) {
return (actualCount === undefined) || (actualCount === optionCount);
},

byPrice: function (actualPrice, optionPrice) {
return (actualPrice === undefined) || (actualPrice === optionPrice);
}
};
return this.products.filter(
(product) => filters.byName(product.name, optionName)
|| filters.byCount(product.count, optionCount)
|| filters.byPrice(product.price, optionPrice));
}
}
const shop = new Shop();
shop.addProduct(new Product("product 1", 1, 2000));
shop.addProduct(new Product("item 2", 2, 100));
shop.addProduct(new Product("some 3", 3, 500));
shop.addProduct(new Product("anything 4", 4, 1000));
console.log(shop.filterProductBy({
name: "product 1",
count: ">1",
price: ">=500"

}));

最佳答案

您可以使用一个对象,其中运算符作为键,函数作为值,例如

var operators = {
'===': function (a, b) { return a === b; },
'==': function (a, b) { return a == b; },
'<=': function (a, b) { return a <= b; },
'>=': function (a, b) { return a >= b; },
'<': function (a, b) { return a < b; },
'>': function (a, b) { return a > b; }
};

使用时,采用分隔的运算符和要比较的两个值。

您可以省略对运算符的检查并采用函数作为值,例如

return operators[operator](leftValue, rightValue);

关于javascript - 如何将字符串解析为比较运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50776046/

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