Dmitry Minkovsky
Dmitry Minkovsky

Reputation: 38143

Is it possible to write this function non-recursively and without the redundant line?

I've been wondering whether I can eliminate the duplicate line in the function below, but have not be able to arrive at a non-recursive solution.

Just out of curiosity, is there a way to eliminate the duplicate line, but without recursion?

function accumulateOverProtos(obj, propName) {
  var accumulator = []                                                                                                                                                                       
  if (obj.hasOwnProperty(propName)) accumulator.push(obj[propName])                                                                                                                          
  while (obj = Object.getPrototypeOf(obj)) {                                                                                                                                                 
    if (obj.hasOwnProperty(propName)) accumulator.push(obj[propName])                                                                                                                        
  }                                                                                                                                                                                          
  return accumulator                                                                                                                                      
}

Also, could anyone point me to some reading on this sort of thing? What is this issue/problem called?

Upvotes: 0

Views: 62

Answers (2)

James Montagne
James Montagne

Reputation: 78650

A perfect use case for do...while.

function accumulateOverProtos(obj, propName) {
    var accumulator = [];

    do {
        if (obj.hasOwnProperty(propName)) accumulator.push(obj[propName]);
    } while (obj = Object.getPrototypeOf(obj));

    return accumulator;
}

Upvotes: 3

Pointy
Pointy

Reputation: 413737

You could just use a simple for loop:

function accumulateOverProtos(obj, propName) {
  var accumulator = [];                                                         
  for (; obj; obj = Object.getPrototypeOf(obj))
    if (obj.hasOwnProperty(propName)) accumulator.push(obj[propName]);
  return accumulator;
}

Upvotes: 1

Related Questions