3

I'm new to immutable.js, and for the life of me I can't figure out how to iterate over the map / list that results form using 'fromJS' on my state object.

How would I go about calculating the total of the cart in the example below? Cart syntax is: {productId: quantity, productId: quantity, productId.. etc

    const INITIAL_STATE = fromJS({
      products: [
        {id: 1, name:'spaghetti', price: 25.00},
        {id: 2, name:'gold', price: 20.00},
        {id: 3, name:'rake', price: 15.00},
        {id: 4, name:'car', price: 10.00},
        {id: 5, name:'falcon', price: 5.00}
      ],
      cart: {1: 4, 3: 7}
    })

How do you iterate through immutable objects here? The methods promoted here are light on detail to my junior eye: https://facebook.github.io/immutable-js/docs/#/List/keys

I think I found a solution, bit of a hack though:

const total = () => {
 let total =0
 state.get('products')
   .filter( p => {
     return state.get('cart')
       .has(p.get('id').toString())
   })
   .map( p => {
     total += state.get('cart')
      .get(p.get('id').toString())
      * p.get('price')
   })
 return total
}

1 Answer 1

3

The below will work, it's slightly terser.

const total = state.get('cart').reduce((total, quantity, id) => {
  const price = state.get('products').find(product => product.get('id') == id).get('price');
  total += price * quantity;
  return total;
}, 0);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.