Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const orders = [
- {
- id: 123,
- name: 'Alex',
- age: 32,
- cart: [
- {
- productId: 234,
- price: 23.99,
- quantity: 3,
- },
- {
- productId: 235,
- price: 39.99,
- quantity: 4,
- },
- ],
- },
- {
- id: 124,
- name: 'Steve',
- age: 22,
- cart: [
- {
- productId: 234,
- price: 23.99,
- quantity: 1,
- },
- ],
- },{
- id: 125,
- name: 'Joe',
- age: 43,
- },
- ];
- const findCustomer = customerName => {
- const customer = orders.find(order => order.name === customerName);
- if (!customer) throw new Error('Customer not found');
- return customer;
- }
- const totalOrderValue = (customerName) => {
- try {
- const customer = findCustomer(customerName);
- if (!customer.cart) {
- return 0;
- }
- const reducer = (sum, {quantity, price}) => sum += quantity * price;
- return customer.cart.reduce(reducer, 0);
- } catch (error) {
- console.log(error.message);
- }
- }
- console.log(totalOrderValue('Alex')); // 231.93
- console.log(totalOrderValue('Steve')); // 23.99
- console.log(totalOrderValue('Joe')); // 0
- console.log(totalOrderValue('Wally')); // show an error
- const invoiceForCustomer = (customerName) => {
- try {
- const customer = findCustomer(customerName);
- if (!customer.cart) {
- return [];
- }
- return customer.cart.map(({quantity, price}) => quantity * price);
- } catch (error) {
- console.log(error.message);
- }
- }
- console.log(invoiceForCustomer('Alex')); // [ 71.97, 159.96 ]
- console.log(invoiceForCustomer('Steve')); // [ 23.99 ]
- console.log(invoiceForCustomer('Joe')); // []
- console.log(invoiceForCustomer('Wally')); // show an error
Add Comment
Please, Sign In to add comment