const towers = [
{ id: 3, name: 'N3', quantity: 430 },
{ id: 4, name: 'N4', quantity: 60 },
{ id: 5, name: 'N5', quantity: 90 },
{ id: 6, name: 'N6', quantity: 140 },
{ id: 7, name: 'N7', quantity: 250 },
]
function divide(towers, quantityPerTable) {
const result = []
let currentGroup = null
const resetGroup = () => currentGroup = { total: 0, towers: [] }
const addTower = t => {
currentGroup.towers.push(t)
currentGroup.total += t.quantity
}
const completeGroup = () => {
console.log('completed', currentGroup)
let tempTotal = currentGroup.total
if (tempTotal > quantityPerTable) {
let tTower = currentGroup.towers[0]
splitTower(tempTotal, tTower)
} else {
// console.log('2', currentGroup)
result.push(currentGroup)
}
resetGroup()
}
const splitTower = (tempTotal, tTower) => {
let tempTower ={
...tTower
}
if(tempTotal <= 0){
return
}
if (tempTotal >= quantityPerTable) {
const tempGroup = { total: 0, towers: [] }
tempGroup.total = quantityPerTable
tempTower.quantity = quantityPerTable
tempGroup.towers.push(tempTower)
result.push(tempGroup)
splitTower((tempTotal-quantityPerTable).toFixed(3), tTower)
} else {
const tempGroup = { total: 0, towers: [] }
tempGroup.total = tempTotal
tempTower.quantity = tempTotal
tempGroup.towers.push(tempTower)
result.push(tempGroup)
}
// console.log('tempTotal', tempTower)
}
resetGroup()
towers.forEach((tower, index) => {
if (currentGroup.total >= quantityPerTable) {
completeGroup()
}
if (
currentGroup.towers.length > 0
) {
completeGroup()
}
addTower(tower)
if (index === towers.length - 1) {
completeGroup()
}
})
return result
}
console.log(divide(towers, 100))
console