Last active
September 14, 2022 09:57
-
-
Save mihailgaberov/5faa2c1c3e4fd3e0593ad68861b989ce to your computer and use it in GitHub Desktop.
Grouping price levels by ticket size
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 levels = [ | |
[1001, 1], | |
[1000.5, 1], | |
[1000, 1], | |
[999, 1], | |
[988.5, 1], | |
[988, 1] | |
] */ | |
const levels = [ | |
[50163, 110], | |
[50162, 13140], | |
[50158, 3763], | |
[50156, 1570], | |
[50155, 21997], | |
[50152.5, 450], | |
[50151, 4669], | |
[50150.5, 10329], | |
[50150, 2500], | |
[50149.5, 450], | |
[50149, 4022], | |
[50148, 20000], | |
[50147, 5166], | |
[50146.5,5274], | |
[50145,174609], | |
[50143, 20000], | |
[50141, 28000], | |
[50140.5,5000], | |
[50138, 6000], | |
[50132.5,4529], | |
[50132, 4755], | |
[50131, 12483], | |
[50128.5,61115], | |
[50128, 23064], | |
[50125.5,181363] | |
] | |
/** | |
* Returns the number rounded to the nearest interval. | |
* Example: | |
* | |
* roundToNearest(80, 100); // 100 | |
* roundToNearest(25, 15); // 30 | |
* | |
* @param {number} value The number to round | |
* @param {number} interval The numeric interval to round to | |
* @return {number} | |
*/ | |
function roundToNearest(value, interval) { | |
return Math.floor(value / interval) * interval; | |
} | |
function groupByPrice(levels) { | |
return levels.map((level, idx) => { | |
const nextLevel = levels[idx + 1]; | |
const prevLevel = levels[idx - 1]; | |
if(nextLevel && level[0] === nextLevel[0]) { | |
return [level[0], level[1] + nextLevel[1]] | |
} else if(prevLevel && level[0] === prevLevel[0]) { | |
return []; | |
} else { | |
return level; | |
} | |
}).filter(el => el.length > 0); | |
} | |
function groupByTicketSize(levels, ticketSize) { | |
return groupByPrice(levels.map(level => [roundToNearest(level[0], ticketSize), level[1]])); | |
} | |
// console.log(groupByTicketSize(levels, 0.5)); | |
// console.log(groupByTicketSize(levels, 1)); | |
// console.log(groupByTicketSize(levels, 2.5)); | |
console.log(groupByPrice([ [1000, 100], [1000, 200], [993, 20] ])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment