@aeldar/rounded-percentage
A function roundedPercentage
, which takes a list of items with percentages and returns the list of tuples of original items and rounded percentages.
The Largest Remainder Method is used to calculate rounded percentage keeping the sum of them correct (added up to 100%).
Signature
function roundedPercentage<T>(selector: (x: T) => number, xs: T[]): [T, number][];
Params
-
selector
: a function to extract the real percentage value from every list item. -
xs
: an array of items with percentages. Can be any type that can be converted to a number with the providedselector
.
Return value
A list of tuples [x, p]
where:
-
x
is the original item from the list (which is the input paramxs
). The reference is kept in case of anobject
item, thus can be used for shallow comparison. -
p
is the rounded percentage for that item's real percentage.
ATTENTION! The initial order of items is not preserved.
Usage examples
import { roundedPercentage } from '@aeldar/rounded-percentage';
const percentages = [8.3, 1.1, 3.6, 2.25, 2.25, 2.25, 2.25, 64.8, 13.2];
const roudedPercentages = roundedPercentage(x => x, percentages);
console.log(roudedPercentages);
// [
// [8.3, 9], [1.1, 1], [3.6, 4], [2.25, 2], [2.25, 2], [2.25, 2], [2.25, 2], [64.8, 65], [13.2, 13]
// ]