Wednesday, June 14, 2017

Inventory by Functional Javascript

The purpose of this exercise is to learn how to use forEach, map and reduce together.

First, create the inventory data structure then the two functions that wrap map and reduce.

Then refine the use of the data structure and the functions until we get the result we desire, the value of the all the items by brand.
> var inventory = [
    { brand: 'Nike',    
      items: [
        {name: 'Air Jordan', price: 100}, 
        {name: 'Air Max', price: 120}
      ]
    },
    { brand: 'Adidas', 
      items: [
        {name: 'Super Star', price: 99}, 
        {name: 'Racer', price: 151}
      ]
    }
  ];

> var computeSum = function(valuesMap) {
    return valuesMap.reduce(function(tot, val) { return tot + val; }, 0);
  }

> var computeTotalCost = function(items) {
    var prices = items.map(function(item) { return item.price; });
    return computeSum(prices);
  }

> computeTotalCost(inventory[0].items)
  220

> computeTotalCost(inventory[1].items)
  250

> inventory.forEach(function(elem) {console.log(elem.brand)})
  Nike
  Adidas

> inventory.forEach(
    function(elem) {
      elem.items.forEach(
       function(item) {
         console.log(item.price )
       }
     )
    }
  )
  100
  120
  99
  151

> inventory.forEach(
    function(elem) {
      console.log(elem.brand + ": " + computeTotalCost(elem.items))
    }
  )
  Nike: 220
  Addidas: 250


The last step produces the info we need, the brand name and the value of the inventory. What we do now is make the values portable by creating a new object inventoryTotals and, using the functions that wrap map and reduce, place the brand name and total for that brand in it.

> inventoryTotals = {};

> inventory.forEach(
    function(elem) {
      inventoryTotals[elem.brand] = computeTotalCost(elem.items);
    }
  )

> inventoryTotals
  Object {Nike: 220, Addidas: 250}