Last active
February 1, 2016 20:53
-
-
Save mlms13/44f7cece6d4bd593e83e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var sections = [{ | |
id: "A", | |
flag: false, | |
subsections: [{ | |
id: "A1", | |
subsections: [{ | |
id: "A1a", | |
flag: true | |
}, { | |
id: "A1b" | |
}] | |
}, { | |
id: "A2" | |
}, { | |
id: "A3", | |
flag: false | |
}] | |
}, { | |
id: "B", | |
flag: true | |
}]; | |
var item = { | |
name: "Foo", | |
sectionId: "A1b" | |
}; | |
/** | |
* Recursively dig through subsections until we find one that matches `id`. | |
* When a match is found, return the flag preference for that section or its | |
* nearest ancestor. | |
* | |
* `id` is a String section id | |
* `current` is a single Section like the ones above | |
* `siblings` is an array of other sections at the same level as `current` | |
* `preferred` is a Bool, tracking the current preference | |
* | |
**/ | |
function getSectionPreferredType(id, current, siblings, preferred) { | |
var sectionPreferred = current.flag != null ? current.flag : preferred; | |
if (current.id == id) { | |
// if we found the matching section, return the closest section's flag | |
return sectionPreferred; | |
} | |
if (current.subsections != null && current.subsections.length > 0) { | |
// depth-first, look through each child section for a match | |
var found = getSectionPreferredType(id, current.subsections[0], current.subsections.slice(1), sectionPreferred); | |
if (found != null) return found; | |
} | |
if (siblings != null && siblings.length > 0) { | |
// if we've found no matches so far, check the next child, using the | |
// `preferred` that was passed in from the parent | |
return getSectionPreferredType(id, siblings[0], siblings.slice(1), preferred); | |
} | |
return null; | |
} | |
getSectionPreferredType("A1b", sections[0], sections.slice(1)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment