feat: add configurable credit calculation with validation
This commit is contained in:
36
src/lib/credits.js
Normal file
36
src/lib/credits.js
Normal file
@@ -0,0 +1,36 @@
|
||||
"use strict";
|
||||
|
||||
function assertPositiveInt(name, value) {
|
||||
if (!Number.isInteger(value) || value <= 0) {
|
||||
throw new Error(`${name} must be a positive integer`);
|
||||
}
|
||||
}
|
||||
|
||||
function validateCreditConfig(config) {
|
||||
assertPositiveInt("baseCredits", config.baseCredits);
|
||||
assertPositiveInt("includedChars", config.includedChars);
|
||||
assertPositiveInt("stepChars", config.stepChars);
|
||||
assertPositiveInt("stepCredits", config.stepCredits);
|
||||
assertPositiveInt("maxCharsPerArticle", config.maxCharsPerArticle);
|
||||
}
|
||||
|
||||
function calculateCredits(charCount, config) {
|
||||
validateCreditConfig(config);
|
||||
|
||||
if (!Number.isInteger(charCount) || charCount <= 0) {
|
||||
throw new Error("charCount must be a positive integer");
|
||||
}
|
||||
|
||||
if (charCount > config.maxCharsPerArticle) {
|
||||
throw new Error("article_too_long");
|
||||
}
|
||||
|
||||
const overage = Math.max(0, charCount - config.includedChars);
|
||||
const extraSteps = overage === 0 ? 0 : Math.ceil(overage / config.stepChars);
|
||||
return config.baseCredits + (extraSteps * config.stepCredits);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
calculateCredits,
|
||||
validateCreditConfig,
|
||||
};
|
||||
Reference in New Issue
Block a user