Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 99 additions & 0 deletions src/lib/gamification/badge-progress.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
export type BadgeTierName = 'none' | 'bronze' | 'silver' | 'gold' | 'diamond';

export interface BadgeProgressReport {
currentCount: number;
currentTier: BadgeTierName;
nextTier: BadgeTierName | null;
/** Target count required for next tier, or null if maximum tier unlocked */
nextTierThreshold: number | null;
/** Remaining count to unlock the next tier (0 if maxed out) */
remainingCount: number;
/** Percentage (0 to 100, rounded to 1 decimal place) completed toward next tier */
progressPercentage: number;
}

export const DEFAULT_BADGE_THRESHOLDS: Record<BadgeTierName, number> = {
none: 0,
bronze: 5,
silver: 25,
gold: 50,
diamond: 100,
};

/** Tiers ordered from lowest to highest. */
const TIER_ORDER: BadgeTierName[] = ['none', 'bronze', 'silver', 'gold', 'diamond'];

/**
* Calculates which badge tier the current count falls into, along with
* progress toward unlocking the next tier.
*
* @param currentCount - Number of completed habit check-ins.
* @param customThresholds - Optional overrides for tier unlock thresholds.
*/
export function calculateBadgeProgress(
currentCount: number,
customThresholds?: Partial<Record<BadgeTierName, number>>,
): BadgeProgressReport {
if (typeof currentCount !== 'number' || !Number.isFinite(currentCount)) {
throw new TypeError('currentCount must be a finite number.');
}
if (currentCount < 0) {
throw new RangeError('currentCount must be a non-negative number.');
}

const thresholds: Record<BadgeTierName, number> = {
...DEFAULT_BADGE_THRESHOLDS,
...customThresholds,
};
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

// Validate every merged threshold before scanning tiers.
for (const tier of TIER_ORDER) {
const threshold = thresholds[tier];
if (typeof threshold !== 'number' || !Number.isFinite(threshold)) {
throw new TypeError(`Threshold for ${tier} must be a finite number.`);
}
if (threshold < 0) {
throw new RangeError(`Threshold for ${tier} must be a non-negative number.`);
}
}

// Find the highest tier whose threshold has already been reached.
let currentIndex = 0;
for (let i = TIER_ORDER.length - 1; i >= 0; i -= 1) {
if (currentCount >= thresholds[TIER_ORDER[i]]) {
currentIndex = i;
break;
}
}
const currentTier = TIER_ORDER[currentIndex];

// Already at the maximum tier (diamond).
if (currentIndex === TIER_ORDER.length - 1) {
return {
currentCount,
currentTier,
nextTier: null,
nextTierThreshold: null,
remainingCount: 0,
progressPercentage: 100,
};
}

const nextTier = TIER_ORDER[currentIndex + 1];
const nextTierThreshold = thresholds[nextTier];
const currentTierThreshold = thresholds[currentTier];
const remainingCount = nextTierThreshold - currentCount;
const span = nextTierThreshold - currentTierThreshold;
const progressPercentage = span > 0
? Math.max(0, Math.min(100, Math.round(((currentCount - currentTierThreshold) / span) * 1000) / 10))
: 100;

return {
currentCount,
currentTier,
nextTier,
nextTierThreshold,
remainingCount,
progressPercentage,
};
}
142 changes: 142 additions & 0 deletions tests/badge-progress.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';

import { calculateBadgeProgress } from '../src/lib/gamification/badge-progress';

describe('calculateBadgeProgress', () => {
it('starts at none with a zero count', () => {
assert.deepStrictEqual(calculateBadgeProgress(0), {
currentCount: 0,
currentTier: 'none',
nextTier: 'bronze',
nextTierThreshold: 5,
remainingCount: 5,
progressPercentage: 0,
});
});

it('unlocks bronze exactly at the bronze threshold', () => {
assert.deepStrictEqual(calculateBadgeProgress(5), {
currentCount: 5,
currentTier: 'bronze',
nextTier: 'silver',
nextTierThreshold: 25,
remainingCount: 20,
progressPercentage: 0,
});
});

it('calculates mid progress within bronze', () => {
const result = calculateBadgeProgress(15);

assert.strictEqual(result.currentTier, 'bronze');
assert.strictEqual(result.nextTier, 'silver');
assert.strictEqual(result.remainingCount, 10);
assert.strictEqual(result.progressPercentage, 50);
});

it('is almost at silver right before the silver threshold', () => {
const result = calculateBadgeProgress(24);

assert.strictEqual(result.currentTier, 'bronze');
assert.strictEqual(result.nextTier, 'silver');
assert.strictEqual(result.remainingCount, 1);
assert.strictEqual(result.progressPercentage, 95);
});

it('rounds progress to one decimal place', () => {
const result = calculateBadgeProgress(6, { silver: 11 });

assert.strictEqual(result.currentTier, 'bronze');
assert.strictEqual(result.progressPercentage, 16.7);
});

it('unlocks silver exactly at the silver threshold', () => {
assert.deepStrictEqual(calculateBadgeProgress(25), {
currentCount: 25,
currentTier: 'silver',
nextTier: 'gold',
nextTierThreshold: 50,
remainingCount: 25,
progressPercentage: 0,
});
});

it('handles counts just below the gold and diamond milestones', () => {
const beforeGold = calculateBadgeProgress(49);
assert.strictEqual(beforeGold.currentTier, 'silver');
assert.strictEqual(beforeGold.remainingCount, 1);

const beforeDiamond = calculateBadgeProgress(99);
assert.strictEqual(beforeDiamond.currentTier, 'gold');
assert.strictEqual(beforeDiamond.remainingCount, 1);
});

it('unlocks gold exactly at the gold threshold', () => {
assert.deepStrictEqual(calculateBadgeProgress(50), {
currentCount: 50,
currentTier: 'gold',
nextTier: 'diamond',
nextTierThreshold: 100,
remainingCount: 50,
progressPercentage: 0,
});
});

it('calculates mid progress within gold', () => {
const result = calculateBadgeProgress(75);

assert.strictEqual(result.currentTier, 'gold');
assert.strictEqual(result.nextTier, 'diamond');
assert.strictEqual(result.remainingCount, 25);
assert.strictEqual(result.progressPercentage, 50);
});

it('maxes out at diamond on the diamond threshold', () => {
assert.deepStrictEqual(calculateBadgeProgress(100), {
currentCount: 100,
currentTier: 'diamond',
nextTier: null,
nextTierThreshold: null,
remainingCount: 0,
progressPercentage: 100,
});
});

it('stays maxed out above the maximum threshold', () => {
const result = calculateBadgeProgress(150);

assert.strictEqual(result.currentTier, 'diamond');
assert.strictEqual(result.nextTier, null);
assert.strictEqual(result.nextTierThreshold, null);
assert.strictEqual(result.remainingCount, 0);
assert.strictEqual(result.progressPercentage, 100);
});

it('honors custom thresholds', () => {
const result = calculateBadgeProgress(10, { bronze: 10, silver: 30 });

assert.strictEqual(result.currentTier, 'bronze');
assert.strictEqual(result.nextTier, 'silver');
assert.strictEqual(result.nextTierThreshold, 30);
assert.strictEqual(result.remainingCount, 20);
});

it('rejects a non-finite custom threshold with TypeError', () => {
assert.throws(() => calculateBadgeProgress(0, { bronze: Number.NaN }), TypeError);
assert.throws(() => calculateBadgeProgress(0, { silver: Infinity }), TypeError);
});

it('rejects a negative custom threshold with RangeError', () => {
assert.throws(() => calculateBadgeProgress(0, { bronze: -1 }), RangeError);
});

it('rejects a negative count with RangeError', () => {
assert.throws(() => calculateBadgeProgress(-1), RangeError);
});

it('rejects a non-finite count with TypeError', () => {
assert.throws(() => calculateBadgeProgress(Number.NaN), TypeError);
assert.throws(() => calculateBadgeProgress(Infinity), TypeError);
});
});
Loading