0

I have a Class containing keys, values and children like this

class Container{
    key: string,
    value: string,
    children: Container[]
}

function searchKey(container: Container, key:string){
    if (container.key == key) {
        return container;
    }
    else if (container.children.length>0){
        for (let child of container.children) {
            let found = searchKey(child, key);
            if (found != null) {
                return found;
            }
        }
    }
    return null;
} 

Input which I will be supplying to searchKey() function would be an array with deep objects and I want to get value for the supplied key parameter. But the current searchKey() function would not accept an array. How to make it to work with an array as input?

Protagonist
  • 1,649
  • 7
  • 34
  • 56

1 Answers1

1

Your searchKey() function currently accepts a single Container and checks it for a match against key. If it fails, it iterates through the children array of Containers and calls itself recursively on each one.

If you only intend to call the function with an array of Container and never need to pass in a single Container, then you can turn the function inside-out like this:

function searchKey(containers: Container[], key: string): Container | null {
  if (containers.length > 0) {
    for (let container of containers) {
      if (container.key == key) {
        return container;
      } else {
        let found = searchKey(container.children, key);
        if (found != null) {
          return found;
        }
      }
    }
  }
  return null;
}

(I tried to keep the above function in the same style as your original.)

This searchKey() function starts off by iterating through an array of Containers. It checks each Container for a key match, and if it doesn't find it, it calls itself recursively on the children array.


There are other ways of doing this, of course. Examples:

  • two mutually recursive functions;
  • a single dual-purpose function that accepts Container | Container[] arguments;
  • a simple shim which calls your existing searchKey() with a dummy Container object whose children is the array you want.

Which one is best depends on your use case.

Hope that helps; good luck.

jcalz
  • 264,269
  • 27
  • 359
  • 360