【问题标题】:Extend algorithm that based on loop基于循环的扩展算法
【发布时间】:2020-12-11 14:53:53
【问题描述】:

我的算法计算通过 DOM 的路径。它从给定的组件开始,然后向上爬。每次父组件具有特定属性时,算法都会将其值添加到路径中。

_computePath(aComponent) {
  let result = '';
  let parent = aComponent.parentNode;

  while (parent.tagName !== 'MY-ROOT-COMPONENT') {
    if (parent.hasAttribute('my-attribute')) {
      result = `/${parent.getAttribute('my-attribute')}${result}`;
    }
    parent = parent.parentNode;
  }

  return result;
}

在我的应用程序的其他部分,我需要一个稍微不同的版本。

_computePath(aComponent) {
  let result = '';
  let parent = aComponent.parentNode;

  while (parent.tagName !== 'MY-ROOT-COMPONENT') {
    if (parent.tagName === 'SPECIAL-COMPONENT') {
      result = null;
      break;
    }

    if (parent.condition === 'special') {
      result = null;
      break;
    }

    if (parent.hasAttribute('my-attribute')) {
      result = `/${parent.getAttribute('my-attribute')}${result}`;
    }
    parent = parent.parentNode;
  }

  return result;
}

如何在不重复代码的情况下扩展第一个循环的算法?

可能有一个非常简单的解决方案,但不知何故我想不通。

谢谢

【问题讨论】:

    标签: javascript architecture software-design


    【解决方案1】:

    让函数接受一个回调来测试导致它中断的条件。

    _computePath(aComponent, stopfun = parent => false) {
      let result = '';
      let parent = aComponent.parentNode;
    
      while (parent.tagName !== 'MY-ROOT-COMPONENT') {
        if (stopfun(parent)) {
          result = null;
          break;
        }
    
        if (parent.hasAttribute('my-attribute')) {
          result = `/${parent.getAttribute('my-attribute')}${result}`;
        }
        parent = parent.parentNode;
      }
    
      return result;
    }
    
    let result1 = obj1._computePath(component1); // no extra stop check
    let result2 = obj2._computePath(component2, parent => parent.tagName === 'SPECIAL-COMPONENT' || parent.condition === 'special');

    【讨论】:

    • 感谢您的回答。这也是我的第一个想法。但我不确定将由循环修改的引用变量传递给函数是否太“危险”?
    • 该变量未被函数修改。这是参数的默认值,不会修改调用者的变量。
    • JavaScript 不通过引用传递变量。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-10
    • 2017-02-20
    • 2017-01-18
    • 2020-06-01
    相关资源
    最近更新 更多