Skip to content

Instantly share code, notes, and snippets.

@ThomasCBrannan
Last active June 11, 2017 22:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ThomasCBrannan/e6ead761a7a64b9ed86df71ffafac66d to your computer and use it in GitHub Desktop.
Save ThomasCBrannan/e6ead761a7a64b9ed86df71ffafac66d to your computer and use it in GitHub Desktop.
// res is an empty object that holds an array designers: []
// For each designer object in the inventory...
// Add an object to the array in res with name: designer.name
// For each shoe in designer[shoes]...
// Add shoe price to an array of shoe prices
// Get the average of the shoe prices
// Add averagePrice: averageOfShoePrices to the designer's object in res
// return res
function getAverageDesignerPrices(inventory) {
var res = {'designers':[]};
for (var designer of inventory) {
var shoePrices = [];
for (var shoe of designer['shoes']) {
shoePrices.push(shoe['price']);
}
res['designers'].push({'name':designer.name, 'averagePrice':average(shoePrices)});
}
return res;
}
// Find the average of an array of numbers
function average(array) {
var total = 0;
for (var num of array) {
total += num;
}
return total / array.length;
}
var expected = {
'designers': [
{
'name': 'Brunello Cucinelli',
'averagePrice': 1025
},
{
'name': 'Gucci',
'averagePrice': 850
}
]
};
var inventory = [
{
name: 'Brunello Cucinelli',
shoes: [
{name: 'tasselled black low-top lace-up', price: 1000},
{name: 'tasselled green low-top lace-up', price: 1100},
{name: 'plain beige suede moccasin', price: 950},
{name: 'plain olive suede moccasin', price: 1050}
]
},
{
name: 'Gucci',
shoes: [
{name: 'red leather laced sneakers', price: 800},
{name: 'black leather laced sneakers', price: 900}
]
}
];
function assertObjectsEqual(actual, expected, testName) {
var passed = true;
if (Object.keys(actual).length !== Object.keys(expected).length) {
passed = false;
} else {
for (var key in actual) {
if (actual[key] !== expected[key]) {
passed = false;
break;
}
}
}
if (passed) {
console.log('passed');
} else {
console.log('FAILED [' + testName + '], expected ' + JSON.stringify(expected) + ', but got ' + JSON.stringify(actual));
}
}
// Test getAverageDesignerPrice via assertObjectsEqual with provided simple paramaters
assertObjectsEqual(getAverageDesignerPrices(inventory), expected, 'Test with provided input and output')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment