Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- var inventory = {
- '000001': {
- name: 'Banana Slicer',
- price: 2.99
- },
- '000002': {
- name: 'Three Wolves Tea Cozy',
- price: 14.95
- }
- };
- function tenPercentOffOf (obj) {
- obj.price = Math.round(0.9 * obj.price * 100) / 100;
- return obj;
- }
- // INSTRUCTIONS
- //
- // Please refer to the following Javascript variable declaration. When submitting your
- // application, please answer the following three questions at the top of your cover
- // letter, before any salutations or headings.
- //
- // var bargainBananaSlicer = tenPercentOffOf(inventory['000001']);
- //
- // Question 1: After declaring that variable, what is the value of bargainBananaSlicer.price?
- // Question 2: After declaring that variable, what is the price of the Banana Slicer
- // in the inventory object?
- // Question 3: Can you suggest ways to improve this code?
- //ANSWERS
- // Question 1: After declaring that variable, what is the value of bargainBananaSlicer.price
- // Answer 1: 'bargainBananaSlicer.price` would be 2.69
- // Question 2: After declaring that variable, what is the price of the Banana Slicer in the inventory object?
- // Answer 2: Value of banana Slice would be 2.69 Because object passed in the function was not clone or cached into variable
- //so when mutation process it affects the orignal value.
- // Answer 3.
- // Object.assign create a swallow copy of the object.
- /**
- * @param {} obj Object
- * Return Ten percent of price off
- */
- const tenPercentOffOf = (obj) => {
- if (!obj.hasOwnProperty("price")) return console.warn("Property price does not exist");
- return Object.assign({}, obj, {
- price: Math.round(0.9 * obj.price * 100) / 100
- });
- }
- // Sample 2. using lodash _.clone
- // _.clone create a swallow copy of __obj
- /**
- * @param {} obj Object
- * Return Ten percent of price off
- */
- const tenPercentOffOf = (obj) => {
- let obj = _.clone(__obj);
- if (obj.hasOwnProperty("price")) {
- obj.price = Math.round(0.9 * obj.price * 100) / 100;
- return obj;
- } else {
- console.warn("Property price does not exist")
- }
- }
Add Comment
Please, Sign In to add comment