如何使用运算符按字符串数过滤数组?

时间:2018-06-09 09:42:36

标签: javascript

我实现了一种在指定选项上过滤商品的方法。该方法将包含用于搜索的参数的选项对象作为参数,例如:{name:“item 2”,price:“< = 1000”,count:“> 2”},每个选项都是可选的。该方法必须返回带有货物的过滤数组。 filterProductBy(options)。

我设法按名称过滤。告诉我如何正确过滤数字,以便过滤器调用如下所示:

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

代码:

//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));

1 个答案:

答案 0 :(得分:1)

您的问题涉及多个子问题。
我认为最重要的是如何将字符串解析为比较运算符?

这是您可以采取的主要措施:

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);
  }
}


console.log(parseCompOperator(">1", 1));
console.log(parseCompOperator("<=1", 1));
console.log(parseCompOperator(">1", 3));

我正在使用的正则表达式((?:<|>)=?\\d+)匹配比较运算符(><<=>=)的模式,后跟确保输入有效后,我将操作符与数字分开并明确比较它们。