forked from TrainingByPackt/Advanced-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexercise-solution.js
More file actions
25 lines (20 loc) · 759 Bytes
/
exercise-solution.js
File metadata and controls
25 lines (20 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
'use strict';
// Solution:
function addItem( cart, item, quantity ) {
// Duplicate cart
const newCart = JSON.parse( JSON.stringify( cart ) );
newCart.push( ...Array( quantity ).fill( item ) );
return newCart;
}
// Run this code to test your addItem function. If an error is thrown then the code is not correct
const cart = [ 'soap', 'toothpaste', 'toothpaste' ];
const originalLength = cart.length;
const quantityToAdd = 3;
const cartModified = addItem( cart, 'carrot', quantityToAdd );
if ( cart.length !== originalLength ) {
throw new Error( 'Original cart modified' );
}
if ( cartModified.length !== ( originalLength + quantityToAdd ) ) {
throw new Error( 'Did not add items to the new cart' );
}
console.log('No function purity error!');