基于循环的扩展算法

我的算法计算通过 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;

}

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


可能有一个非常简单的解决方案,但不知何故我无法弄清楚。


墨色风雨
浏览 103回答 1
1回答

慕神8447489

让函数接受回调来测试导致其中断的条件。_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 checklet result2 = obj2._computePath(component2, parent => parent.tagName === 'SPECIAL-COMPONENT' || parent.condition === 'special');
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript