扩展了基于循环的算法



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

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

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

谢谢

让函数进行回调,以测试导致其中断的条件。

_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');

最新更新