Skip to content

Instantly share code, notes, and snippets.

@DmitryOlkhovoi
Created March 1, 2018 21:11
Show Gist options
  • Save DmitryOlkhovoi/f25cb7a5033c70ca6bcd25b07bb8f98f to your computer and use it in GitHub Desktop.
Save DmitryOlkhovoi/f25cb7a5033c70ca6bcd25b07bb8f98f to your computer and use it in GitHub Desktop.
index02.js
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