4. Data transformation

by Vitalii_N

HTML

<div id="app"></div>

CSS

.container {
  width: 300px;
  margin: 20px;
}

React

// Your task is to implement generateOrderSummary function

const {createRoot} = ReactDOM;
const {useEffect, useState} = React;

const users = [
  { id: 1, name: 'Alice', age: 30 },
  { id: 2, name: 'Bob', age: 25 },
  { id: 3, name: 'Charlie', age: 35 }
];

const products = [
  { id: 101, name: 'Product A', price: 50 },
  { id: 102, name: 'Product B', price: 100 },
  { id: 103, name: 'Product C', price: 75 }
];

const orders = [
  { id: 1001, userId: 1, productId: 101, quantity: 2 },
  { id: 1002, userId: 2, productId: 102, quantity: 1 },
  { id: 1003, userId: 1, productId: 103, quantity: 3 }
];

const generateOrderSummary = ({ orders, products, users }) => {
	// TODO: it should generate summary for every order
  // so that response will look like this:
  //{
  //  orderId: 1001,
  //  user: { id: 1, name: 'Alice', age: 30 },
  //  product: { id: 101, name: 'Product A', price: 50 },
  //  total: 100 // price * quantity
  //}
  
  // Additional (OPTIONAL) task
  // what is time complexity of your solution?
  // is it possible to make it in O(n) ?
  // rewrite your solution to be the fastest

  // To avoid nested loops we can use maps to prepare data
  
  // O(n)
  const productsMap = products.reduce((map, product) => {
    map[product.id] = product;
    return map;
  }, {});

  // O(n)
  const usersMap = users.reduce((map, user) => {
    map[user.id] = user;
    return map;
  }, {});

  // O(n)
  return orders.map(({id, userId, productId, quantity}) => ({
    orderId: id,
    user: usersMap[userId],
    product: productsMap[productId],
    total: productsMap[productId].price * quantity
  }));
} // O(3n) = O(n)

const Component = () => {
	const [body, setBody] = useState({});
  
  useEffect(() => {
		setBody(generateOrderSummary({ products, orders, users }))
  }, []);
  
	return (
  	<div className="container">
      <pre>{JSON.stringify(body, null, 2)}</pre>
  	</div>
  )
}

const root = createRoot(document.querySelector("#app"));
root.render(<Component/>);