1

So lets say I had a chained sequence like the following:

let amount = _
    .chain(selectedItemsArray)
    .map(item => _.find(availableItems, {id: item.id})
    //how can I determine that ALL items were found right here?
    .filter('price_money')
    ...

Note the comment in the code above. It could be possible that the selectedItemsArray is out of date, so some selected items might not be in availableItems. So, my initial thought was to use a .tap or .thru (probably tap) to do something like _.every(selectedItems, _.isObject) or something similar to catch the error state where not all items are found and throw an error if not all items were found. This feels odd though...any better ways of handling this type of error checking mid sequence?

Something like this does work (at least I can throw an error), but seems like I'm using tap for something it's not intended for:

  .tap(items => {
    if (!_.every(items, _.isObject)) throw new Error('Some selected items are no longer available');
  })
Greg
  • 6,453
  • 9
  • 45
  • 61

1 Answers1

0

You can use another _.filter to check if the element is not an object, and also handle the offending value. You can use || to execute fallback code. See this question.

If you want your code to crash and burn on the first failure, use a function that throws an error instead of using console.error.

var available = [
  { id: 1, amount: 2.00 }, 
  { id: 2, amount: 4.00 }
];
var selected = [1, 2, 3];

var amount = _(selected)
    .map(item => _.find(available, {id:item}) || item)
    .filter(item => _.isObject(item) || console.error("Item not available:", item))
    .sumBy('amount');

console.log("Amount:", amount.toFixed(2));
<script src="https://cdn.jsdelivr.net/lodash/4.15.0/lodash.min.js"></script>
Community
  • 1
  • 1
4castle
  • 32,613
  • 11
  • 69
  • 106