0
votes

I have an array of objects such as: (however my real array is 13000 long)

var items = [
  {
    name: "cat",
    id: "1"
  },
  {
   name: "dog",
    id: "2" 
  }
];

I am trying to iterate over the objects until an object with name is found

however I get maximum call size exceeded when using this large array (13000 size), if I use the array above I get no error.

async code:

function getItemIdByName(itemName, done) {
  async.detect(
    items,
    function hasItemName(item, cb) {
      return cb(null, item.name === itemName);
    },
    function(err, result) {

      if (err) {
        return done(new Error(err));
      }

      if (_.isUndefined(result)) {
        return done(new Error("Item not found"));
      }

      done(null, result);
    });
};

getItemIdByName('Dog', function foundItem(err, itemId) {
  console.log("got error", err);
  console.log("got item", itemId);
});

I get the correct output in the console

got error null
got item { id: 2, name: 'dog' } 

however I also get RangeError: Maximum call stack size exceeded

How can I make this work with my large array of objects?

1
?? Why would you search a list with an asynchronous operation? And why would you use a flat list if you're doing lookups by key? - Pointy
I want to use this for an api endpoint, unfortunately I cannot change the data structure - user2950720
Why not just use .find()? - Pointy

1 Answers

1
votes

Your "iteratee" is synchronous, which is causing the stack exhaustion problem (basically, it's processing all the items in the same "tick", using the same stack frame).

If you want to test your code with a synchronous test setup, you can use async.ensureAsync() to make sure that the iteratee becomes asynchronous:

async.detect(
  items,
  async.ensureAsync(function hasItemName(item, cb) {
    return cb(null, item.name === itemName);
  }),
  ...
);