Last active
May 11, 2024 20:40
-
-
Save ericelliott/43a86f0e7ffb22b6c53f to your computer and use it in GitHub Desktop.
Pure addToCart() https://output.jsbin.com/kaqeter/?html,js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Pure addToCart() returns a new cart | |
// It does not mutate the original. | |
const addToCart = (cart, item, quantity) => { | |
const newCart = lodash.cloneDeep(cart); | |
newCart.items.push({ | |
item, | |
quantity | |
}); | |
return newCart; | |
}; | |
test('addToCart()', assert => { | |
const msg = 'addToCart() should add a new item to the cart.'; | |
const originalCart = { | |
items: [] | |
}; | |
// deep-freeze on npm | |
// throws an error if original is mutated | |
deepFreeze(originalCart); | |
const cart = addToCart( | |
originalCart, | |
{ | |
name: "Digital SLR Camera", | |
price: '1495' | |
}, | |
1 | |
); | |
const expected = 1; // num items in cart | |
const actual = cart.items.length; | |
assert.equal(actual, expected, msg); | |
assert.notDeepEqual(originalCart, cart, | |
'should not mutate original cart.'); | |
assert.end(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment