Вы можете отслеживать, сколько у вас осталось, и использовать Math.min
в вашем map
обратном вызове:
let remaining = limit;
const result = array.map(value => {
value = Math.min(value, remaining);
remaining -= value;
return value;
});
Live Пример:
function test(limit, array, expect) {
let remaining = limit;
const result = array.map(value => {
value = Math.min(value, remaining);
remaining -= value;
return value;
});
const good = result.every((value, index) => value === expect[index]);
console.log(array.join(","), result.join(","), good ? "OK" : "<== Error");
}
const limit = 500;
test(limit, [0], [0]);
test(limit, [300], [300]);
test(limit, [600], [500]);
test(limit, [0,1000], [0, 500]);
test(limit, [600,300], [500,0]);
test(limit, [500,0,0], [500,0,0]);
test(limit, [400,200,0], [400,100,0]);
test(limit, [0,200,300], [0,200,300]);
test(limit, [0,600,300], [0,500,0]);
test(limit, [0,0,600], [0,0,500]);
.as-console-wrapper {
max-height: 100% !important;
}