Created
June 8, 2023 09:53
-
-
Save derakhshanfar/e6050ba22f93dc15782c17c1b95649f7 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
Array.prototype.forEachRecursive = function (callback, startIndex = 0, index = startIndex) { | |
if (index >= this.length) { | |
return; | |
} | |
const shouldContinue = callback(this[index], index, this); | |
if (!shouldContinue) { | |
return; // Break the iteration | |
} | |
this.forEachRecursive(callback, startIndex, index + 1); | |
}; | |
((claims, agents) => { | |
const result = []; | |
let startAgentIndex = 0; | |
claims.forEachRecursive((claim, claimIndex) => { | |
if (!claim) return true; | |
let remainedClaim = claim; | |
const paidBy = []; | |
const cb = (agent, agentIndex, _agents) => { | |
startAgentIndex = agentIndex | |
if (agent.budget >= remainedClaim) { | |
_agents[agentIndex].budget = _agents[agentIndex].budget - remainedClaim; | |
paidBy.push(agent.name); | |
result.push({ claimIndex, paidBy }); | |
return false; // break the loop | |
} else if (agent.budget > 0) { | |
remainedClaim -= agent.budget; | |
_agents[agentIndex].budget = 0; | |
paidBy.push(agent.name); | |
} | |
return true | |
} | |
agents.forEachRecursive(cb, startAgentIndex); | |
return startAgentIndex < agents.length; // Break the iteration in case there is no more agents | |
}); | |
console.log(JSON.stringify(result, null, 2)); | |
})( | |
[14, 10, 20], | |
[ | |
{ name: "a1", budget: 10 }, | |
{ name: "a2", budget: 4 }, | |
{ name: "a3", budget: 40 }, | |
] | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment