DEV Community

loading...

Discussion on: How frontend unit testing turned from a fling to a real thing for me

Collapse
tobiobeck profile image
Tobi Obeck

Hey Miri,
your post is a perfect example why it is important to write tests. Thanks for sharing!
I really liked your dead simple test setup.
At my work place we usually don't write tests, but I sometimes copy a function into jsfiddle to quickly throw in a bunch of inputs to check the expected outcome.

I did so with your problem and had a shot at implementing the algorithm myself.
I noticed that there are further cases that you might not have thought of.
Negative numbers and numbers with a decimal portion result in errors in your implementation.

here is my solution:

function formatNumberAsCurrencyEuro_Tobi(value) {
  if (typeof value === 'string') {
    return value;
  }

  let formattedValue = '';

  // these should be function parameters
  const thousandsSeparator = '.';
  const decimalSeparator = ',';
  const currencyName = 'Euro';

  let valueString = String(_.round(value, 2)); // lodash.round
  let decimalString = '';

  if (valueString.indexOf('.') !== -1) { // has decimal portion
    const splittedValue = valueString.split('.');
    valueString = splittedValue[0];
    decimalString = decimalSeparator + splittedValue[1];
  }

  for (var i = 0; i < valueString.length; i++) {
    var currentChar = valueString[valueString.length - 1 - i];

    if (i !== 0 && i % 3 === 0 && currentChar !== '-') {
      formattedValue = thousandsSeparator + formattedValue;
    }
    formattedValue = currentChar + formattedValue;
  }

  return formattedValue + decimalString + ' ' + currencyName;
}

Another approach would be to simply use the toLocaleString() function.
Probably the easiest and best solution:

function formatNumberAsCurrencyEuro_Locale(number){
  return number.toLocaleString('de-DE', {
    style: 'currency', 
    currency: 'EUR', 
    currencyDisplay: 'name',
    minimumFractionDigits: 0
  });
}

Funnily, even this function has the erroneous test case of -0 as an input.

Whole jsfiddle with running tests:
jsfiddle.net/tobiobeck/p35ebLvs/