javascript - refactoring working recursion code (hasFiveDIVs) for traversing the DOM -
@oriol provided amazing 2 line recursive solution problem working on today.
function numoccurencesrecursive(arr, val) { if (!arr.length) return 0; return (arr[0] === val ? 1 : 0) + numoccurencesrecursive(arr.slice(1), val); }
i inspired refactor spagetti-ish code wrote yesterday:
//returns boolean function containsfiveormoredivs(domelement) { var count = 0; function docount(domelement) { if (domelement && domelement.tagname === "div") { count++; } if (count >= 5) { return true; } if (domelement.haschildnodes()) { var children = domelement.childnodes; (var = 0; < children.length; i++) { if (docount(children[i])) { return true } }; }; return false; } return docount(domelement) } containsfiveormoredivs(document);
here's attempt:
function containsfiveormoredivspurerecursion(domelement) { if (!domelement && domelement.tagname !== "div") { return 0; } return (domelement.tagname === "div" ? 1 : 0) + containsfiveormoredivspurerecursion(domelement.childnodes()); //? }
how loop through child nodes recursively in version? i'm doing possible?
with recursion, should remember return 1 type of value, want return boolean yet want function return count too. complicates things.
heres recursive function count element types
function countelements(domelement, elementtype) { count = (domelement && domelement.tagname === elementtype.touppercase()); if (domelement.haschildnodes()) { (var = 0; < domelement.childnodes.length; i++) { count += countelements(domelement.childnodes[i], elementtype); }; }; return count; }
you can use achieve want.
countelements(document, 'div') >= 5
however, might not efficient way of doing since traverse whole dom tree want stop when you've hit 5 elements.
function containsfiveormoredivspurerecursion(domelement, elementtype) { var count = 0; function countelements(domelement, elementtype) { count += (domelement && domelement.tagname === elementtype.touppercase()); if (count >= 5) return count; if (domelement.haschildnodes()) { (var = 0; < domelement.childnodes.length; i++) { countelements(domelement.childnodes[i], elementtype); }; }; return count; } return countelements(domelement, elementtype) >= 5; }
in example, need keep variable outside of function (thus it's not pure recursion) keep track of count , able return boolean.
Comments
Post a Comment