@aeldar/rounded-percentage
TypeScript icon, indicating that this package has built-in type declarations

1.0.7 • Public • Published

@aeldar/rounded-percentage

npm version Size Status TypeScript MIT License CI Status Featured on Openbase

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 provided selector.

Return value

A list of tuples [x, p] where:

  • x is the original item from the list (which is the input param xs). The reference is kept in case of an object 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]
// ]

Package Sidebar

Install

npm i @aeldar/rounded-percentage

Weekly Downloads

1

Version

1.0.7

License

MIT

Unpacked Size

20.1 kB

Total Files

15

Last publish

Collaborators

  • aeldar