@lunit/oui
Version:
Lunit Oncology UI components
60 lines (59 loc) • 2.14 kB
JavaScript
export function parseStringValToNumber(val) {
const value = val.endsWith('%') ? val.slice(0, -1) : val;
return parseInt(value, 10);
}
export function clampNumericalPercentage(value) {
if (value >= 100)
return 100;
if (value <= 0)
return 0;
return value;
}
export function clampBarLabelPosition(value) {
if (value >= 100)
return 97;
if (value <= 0)
return 1;
return value;
}
const round = (value) => Math.round(value * 10) / 10;
/**
* @description normalizeSegmentWidths is a function that normalizes the width of the segments in the analysis bar.
* @param segments - The segments to normalize.
* @param isCutoff - Whether the analysis bar is a cutoff.
* @returns The normalized segments.
*/
export function normalizeSegmentWidths(segments, isCutoff) {
if (isCutoff)
return segments;
let validSegments = segments
.map((segment) => ({ ...segment, width: round(segment.width) }))
.filter((segment) => segment.width > 0);
if (validSegments.length === 0)
return [];
const normalize = (segments) => {
const total = segments.reduce((sum, s) => sum + s.width, 0);
if (total === 0 || Math.abs(total - 100) < 0.1)
return segments;
const normalized = segments.map((segment) => ({
...segment,
width: round((segment.width / total) * 100),
}));
const normalizedTotal = normalized.reduce((sum, s) => sum + s.width, 0);
const difference = 100 - normalizedTotal;
if (normalized.length > 0 && Math.abs(difference) > 0.01) {
const lastIndex = normalized.length - 1;
normalized[lastIndex] = {
...normalized[lastIndex],
width: round(normalized[lastIndex].width + difference),
};
}
return normalized;
};
validSegments = normalize(validSegments);
const filtered = validSegments.filter((segment) => segment.width > 0);
if (filtered.length < validSegments.length && filtered.length > 0) {
return normalize(filtered);
}
return filtered;
}