Created
March 1, 2018 21:10
-
-
Save DmitryOlkhovoi/2442d5f5ff827cbb27d7e56e75c17306 to your computer and use it in GitHub Desktop.
index01.js
This file contains 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
const products = [ | |
{id: 1, price: 10}, {id: 2, price: 11}, {id: 3, price: 1}, | |
{id: 4, price: 3}, {id: 5, price: 1}, {id: 6, price: 8}, | |
{id: 7, price: 3}, {id: 8, price: 0}, {id: 9, price: 4}, | |
{id: 10, price: 5}, {id: 11, price: 9}, {id: 12, price: 13}, | |
]; | |
const getFirstItems = (products, size) => { | |
return products.slice(0, size) | |
} | |
const getLastItems = (products, size) => { | |
return products.slice(-(size)) | |
} | |
const getHighestAndLowestItems = (products, size) => { | |
if (size === 0) { | |
return { | |
highest: null, | |
lowest: null, | |
} | |
} | |
return { | |
highest: getFirstItems(products, size), | |
lowest: getLastItems(products, size) | |
} | |
} | |
const sortItems = (products) => { | |
return products.sort((a, b) => { | |
if (a.price < b.price) { | |
return 1 | |
} | |
if (b.price < a.price) { | |
return -1 | |
} | |
return 0 | |
}) | |
} | |
/** | |
* @params [Array] products - list of products | |
* @params [Number] options.size - Optional parameter. By default it should be 5 | |
**/ | |
function sortProducts(products, options = { size: 5 }) { | |
const size = options.size >= 0 ? options.size : 5 | |
return getHighestAndLowestItems(sortItems(products), size) | |
} | |
const result = sortProducts(products); // {highest: [...], lowest: [...]} | |
// Sorry guys, don't have much time left to write real world Unit tests :( | |
// toEql (jest) | |
expect(sortProducts(products)).toEql(expectedResult) // highest.len = 5, lowest.len = 5 | |
expect(sortProducts(products, { size: -10 })).toEql(expectedResult) // highest.len = 5, lowest.len = 5 | |
expect(sortProducts(products, { size: 2 })).toEql(expectedResult) // highest.len = 2, lowest.len = 2 | |
expect(sortProducts(products, { size: 0 })).toEql(expectedResult) // highest = null, lowest = null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment