format numbers

by lovinglobo

JavaScript

const billion = x => x*1000000000;
const million = x => x*1000000;
const thousand = x => x*1000;

/**
For which minimum delta do we choose what adjusment?
An adjustment is basically dividing the to be formatted value by the adjustment
value and adding the suffix, e.g. 1000 becomes 1k.
*/
const BIG_NUMBER_ADJUSTMENT_TABLE =[
	{ minimum_largest: billion(1)+1, suffix: 'b', adjustment: billion(1) },
	{ minimum_largest: million(1)+1, suffix: 'm', adjustment: million(1) },
	{ minimum_largest: thousand(10)+1, suffix: 'k', adjustment: thousand(1) },
];

/**
For which minimum delta do we choose what level of precision? 
Any delta bigger than the smallest minimum_delta 
will be formatted with scienitifc notation.
*/
const PRECISION_TABLE = [
	{ minimum_delta: 1000, small_precision: 0, large_precision: 2 },
  { minimum_delta: 10, small_precision: 2, large_precision: 4 },
  { minimum_delta: 1, small_precision: 4, large_precision: 7 },
  { minimum_delta: 0.01, small_precision: 5, large_precision: 7 },
];


/**
Formats numbers based on the range that they are in and the given size, such that:
 - big numbers are adjusted downward using BIG_NUMBER_ADJUSTMENT_TABLE when size equals small
 	- do not adjust for size large
 - if the range goes above 1000 or below -1000 we always get precision 2, large or small
 - small numbers are set to a precision using PRECISION_TABLE, which differs for the two sizes
 - even smaller numbers will use scientific notation with precision 2 or 5 dependending on the size
 - zero is always displayed as '0' 
*/
function formatNumber(min, max, value, size) {
	if (value === 0) return '0';

	const delta = Math.abs(max - min);
	
  const largest = Math.max(Math.abs(min), Math.abs(max));
	const adjustment_row = size === 'small'? BIG_NUMBER_ADJUSTMENT_TABLE.find(a => largest >= a.minimum_largest) : undefined;
  
  const adjusted_value = adjustment_row ? value / adjustment_row.adjustment : value;
  const adjusted_delta = adjustment_row ? delta /...