【问题标题】:Simplify Pattern Matching in Javascript简化 Javascript 中的模式匹配
【发布时间】:2020-07-03 10:09:51
【问题描述】:

我正在尝试使用 JavaScript 实现模式匹配,并希望寻求建议。模式是根据对象参数的存在来计算的。我认为当前的伪代码过于冗长。有什么办法可以简化它吗? (请忽略 Param1 和 Param2)

伪代码:

Pattern1: if null(3,4,5,6)      
Pattern2: if notNull(3,4,5,6)       
Pattern3: if notNull(6) and null(3,4,5)     
Pattern4: if notNull(5) and null(3,4,6)     
Pattern5: if notNull(4) and null(3,5,6)     
Pattern6: if notNull(3) and null(4,5,6)     
Pattern7: if notNull(5,6) and null(3,4)     
Pattern8: if notNull(4,6) and null(3,5)     
Pattern9: if notNull(3,6) and null(4,5)     
Pattern10: if notNull(4,5) and null(3,4)        
Pattern11: if notNull(3,5) and null(4,6)        
Pattern12: if notNull(3,4) and null(5,6)        
Pattern13: if notNull(3,4,5) and null(6)        
Pattern14: if notNull(3,4,6) and null(5)        
Pattern15: if notNull(3,5,6) and null(4)        
Pattern16: if notNull(4,5,6) and null(3)        

【问题讨论】:

  • 这不是代码……看起来像是代码背后的逻辑。值存储在哪里 - 数组?目的? html? nullnotNull不是javascript中的函数(afaik),如果你想写这些函数,我建议你不要使用保留字(?)“null”。
  • @iAmOren,是的,你是对的。我更正了我的陈述,这是代码背后的逻辑。 param1-6 存储在一个对象中。
  • 好...请详细说明该对象。一个例子会很好。 obj=={"1":"x","2":"o"...}?
  • 您可以对您的数据进行哈希处理,并将该哈希值与您的模式相匹配。它可以像“010011”这样简单的字符串,其中0 为空,1 不为空。然后你可以将它与关联数组进行比较,其中哈希是键,值是需要执行的函数。

标签: javascript pattern-matching


【解决方案1】:

是的;如果

function check(params, ...list) {
  for (let i = 2; i < params.length; ++i) {
    if (params[i] == null) {
      if (list.includes(i)) return false;
    } else if (!list.includes(i)) return false;
  }
  return true;
}

被定义了,那么你可以这样写模式:

Pattern3: if check(arguments, 6)

【讨论】:

    【解决方案2】:

    我使用以下伪代码对其进行了重构。

    patterns = [
        [false,false,false,false],
        [true,true,true,true],
        [false,false,false,true],
        [false,false,true,false],
        [false,true,false,false],
        [true,false,false,false],
        [false,false,true,true],
        [false,true,false,true],
        [true,false,false,true],
        [false,true,true,false],
        [true,false,true,false],
        [true,true,false,false],
        [true,true,true,false],
        [true,true,false,true],
        [true,false,true,true],
        [false,true,true,true],
    ]
    
    patterns.findIndex(pattern => /* do params match? */)
    

    【讨论】:

      猜你喜欢
      • 2014-04-21
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 2011-03-04
      相关资源
      最近更新 更多