Created
March 1, 2018 21:11
-
-
Save DmitryOlkhovoi/f25cb7a5033c70ca6bcd25b07bb8f98f to your computer and use it in GitHub Desktop.
index02.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) => { | |
const toSplice = (size * 2 > products.length) ? | |
products.length - size : size | |
if (toSplice <= 0) { | |
return null | |
} | |
return products.slice(-(toSplice)) | |
} | |
const getHighestAndLowestItems = (products, size) => { | |
if (size > products.length || 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) | |
} | |
// Sorry guys, don't have much time left to write real world Unit tests :( | |
// toEql (jest) | |
expect(sortProducts(products)).toEql(expectedResult) // {highest: Array(5), lowest: Array(5)} | |
expect(sortProducts(products, { size: 0 })).toEql(expectedResult) // {highest: null, lowest: null} | |
expect(sortProducts(products, { size: -10 })).toEql(expectedResult) // {highest: Array(5), lowest: Array(5)} | |
expect(sortProducts(products, { size: 10 })).toEql(expectedResult) // {highest: Array(10), lowest: Array(2)} | |
expect(sortProducts(products, { size: 12 })).toEql(expectedResult) // {highest: Array(12), lowest: null} | |
expect(sortProducts(products, { size: 13 })).toEql(expectedResult) // {highest: null, lowest: null} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment