message: Ligatures: Refactor the `walk.ts` functions
diff: import { FlattenedLookupTree, LookupResult } from './types';
  export default function walkTree(tree: FlattenedLookupTree, sequence: number[], startIndex: number, index: number): LookupResult | undefined {
  - const glyphId = sequence[index];
  - let subtree = tree.get(glyphId);
  + let bestLookup: LookupResult = undefined;
  +
  + while (true) {
  + const subtree = tree.get(sequence[index]);
  if (!subtree) {
  - return undefined;
  + return bestLookup;
  }
  - let lookup = subtree.lookup;
  + bestLookup = chooseBestLookup(bestLookup, subtree.lookup);
  if (subtree.reverse) {
  const reverseLookup = walkReverse(subtree.reverse, sequence, startIndex);
  + bestLookup = chooseBestLookup(bestLookup, reverseLookup);
  + }
  - if (
  - (!lookup && reverseLookup) ||
  - (
  - reverseLookup && lookup && (
  - lookup.index > reverseLookup.index ||
  - (lookup.index === reverseLookup.index && lookup.subIndex > reverseLookup.subIndex)
  - )
  - )
  - ) {
  - lookup = reverseLookup;
  + index++;
  + if (index >= sequence.length || !subtree.forward) {
  + return bestLookup;
  }
  + tree = subtree.forward;
  }
  -
  - if (++index >= sequence.length || !subtree.forward) {
  - return lookup;
  }
  - const forwardLookup = walkTree(subtree.forward, sequence, startIndex, index);
  -
  - if (
  - (!lookup && forwardLookup) ||
  - (
  - forwardLookup && lookup && (
  - lookup.index > forwardLookup.index ||
  - (lookup.index === forwardLookup.index && lookup.subIndex > forwardLookup.subIndex)
  - )
  - )
  - ) {
  - lookup = forwardLookup;
  +function chooseBestLookup(aLookup: LookupResult, bLookup: LookupResult): LookupResult {
  + if (bLookup == null) {
  + return aLookup;
  }
  -
  - return lookup;
  + if (aLookup == null) {
  + return bLookup;
  + }
  + if ((aLookup.index > bLookup.index) || (aLookup.index === bLookup.index && aLookup.subIndex > bLookup.subIndex)) {
  + return bLookup;
  + }
  + return aLookup;
  }
  function walkReverse(tree: FlattenedLookupTree, sequence: number[], index: number): LookupResult | undefined {
  @@ -50,14 +41,10 @@ function walkReverse(tree: FlattenedLookupTree, sequence: number[], index: numbe
  let subtree = tree.get(sequence[index]);
  let lookup: LookupResult | undefined = subtree && subtree.lookup;
  while (subtree) {
  - if (
  - (!lookup && subtree.lookup) ||
  - (subtree.lookup && lookup && lookup.index > subtree.lookup.index)
  - ) {
  - lookup = subtree.lookup;
  - }
  + lookup = chooseBestLookup(lookup, subtree.lookup);
  - if (--index < 0 || !subtree.reverse) {
  + --index;
  + if (index < 0 || !subtree.reverse) {
  break;
  }
  