Bookmark this: tool.io/proportions/ratio/source-code
Ratio and Proportion Calculator Source Code
Browse the implementation files for Ratio and Proportion Calculator.tool.ts typescript
// Tool: Ratio and Proportion Calculator
//
// Solves the missing value in A:B = C:D from three positive known values.
// Returns an empty string on invalid, ambiguous, or non-finite input.
const isMissing = (input: unknown): boolean =>
input === undefined ||
input === null ||
(typeof input === 'string' && input.trim() === '');
const parsePositiveNumber = (input: unknown): number | null => {
if (isMissing(input)) return null;
if (typeof input !== 'string' && typeof input !== 'number') return null;
const value = Number(input);
return Number.isFinite(value) && value > 0 ? value : null;
};
export const ratio = (
inputA: unknown,
inputB: unknown,
inputC: unknown,
inputD: unknown,
): string => {
const inputs = [inputA, inputB, inputC, inputD];
if (inputs.filter((input) => !isMissing(input)).length !== 3) {
return '';
}
const a = parsePositiveNumber(inputA);
const b = parsePositiveNumber(inputB);
const c = parsePositiveNumber(inputC);
const d = parsePositiveNumber(inputD);
let result: number;
if (a === null) {
if (b === null || c === null || d === null) return '';
result = (b * c) / d;
} else if (b === null) {
if (c === null || d === null) return '';
result = (a * d) / c;
} else if (c === null) {
if (d === null) return '';
result = (a * d) / b;
} else if (d === null) {
result = (b * c) / a;
} else {
return '';
}
return Number.isFinite(result) && result > 0 ? String(result) : '';
};
export const Tool: TypeTool = {
name: 'Ratio and Proportion Calculator',
slug: 'proportions/ratio',
intro: 'Calculate the missing value in equivalent ratios A:B = C:D.',
tool: ratio,
i: [
{
example: '3',
help: 'Enter exactly three of the four proportion values.',
label: 'A',
placeholder: 'A',
type: 'number',
},
{
example: '2',
help: 'Enter exactly three of the four proportion values.',
label: 'B',
placeholder: 'B',
type: 'number',
},
{
example: '720',
help: 'Enter exactly three of the four proportion values.',
label: 'C',
placeholder: 'C',
type: 'number',
},
{
example: '480',
help: 'Enter exactly three of the four proportion values.',
label: 'D',
placeholder: 'D',
type: 'number',
},
],
o: [
{
example: '480',
help: 'The calculated missing proportion value.',
label: 'Missing Value',
placeholder: 'Missing value will appear here...',
type: 'number',
render: 'textarea',
},
],
equation: '$$\\frac{A}{B}=\\frac{C}{D},\\quad AD=BC$$',
};
export default Tool;
Description
Browse the implementation files for Ratio and Proportion Calculator.