SiPhox Health - Data transformation

by Victor

HTML

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

CSS

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

React

// Your task is to implement generateOrderSummary function

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 usersMap = new Map(users.map(user => [user.id, user]));
const productsMap = new Map(products.map(product => [product.id, product]));

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
  
  let orderSummary = orders.map(order => {
    const orderUser = usersMap.get(order.userId);
    const orderProduct = productsMap.get(order.productId);
    return {
        orderId: order.id,
        user: orderUser,
        product: orderProduct,
        total: orderProduct.price * order.quantity
    };
  });
  return orderSummary;
}

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

ReactDOM.render(<Component />, document.querySelector("#app"))