Skip to content

Instantly share code, notes, and snippets.

@nemmarramos
Forked from lukealbao/QuickJSQuestion.js
Last active December 21, 2017 10:17
Show Gist options
  • Save nemmarramos/91c7d8ec8922cdf82cfd2609fdefe557 to your computer and use it in GitHub Desktop.
Save nemmarramos/91c7d8ec8922cdf82cfd2609fdefe557 to your computer and use it in GitHub Desktop.
Quick JS Question
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?
// Answer 1: bargainBananaSlicer.price would change to 2.69.
//
// Answer 2: Banana Slicer object in inventory would also change to 2.69.
// Javascript is pass by value but not in array and objects.
// Answer 3: I suggest to create a shallow copy then update the copy and return it.
// There are several ways to do it, see below functions.
// Check sample benchmark for the following functions: http://jsben.ch/TsNfQ
// Using ES6 Object.assign
function tenPercentOffOf (obj) {
return Object.assign({}, obj, { price: Math.round(0.9 * obj.price * 100) / 100});
}
// Using lodash assign, I think it is based on ES6 Object.assign
function tenPercentOffOf (obj) {
return _.assign({}, obj, { price: Math.round(0.9 * obj.price * 100) / 100});
}
// Using lodash copy
function tenPercentOffOf (obj) {
let copy = _.clone(obj);
copy.price = Math.round(0.9 * copy.price * 100) / 100;
return copy;
}
// Using JSON parse and stringify
function tenPercentOffOf (obj) {
var copy = JSON.parse(JSON.stringify(obj));
copy.price = Math.round(0.9 * obj.price * 100) / 100;
return copy;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment