import { assign } from 'ember-platform';

// http://stackoverflow.com/a/2901298
const SEPARATOR_REGEX = /\B(?=(\d{3})+(?!\d))/g;

const DEFAULT_OPTIONS = { separator: ',' };

export default function formatNumber(number, optionOverrides = {}) {
  let options = assign(assign({}, DEFAULT_OPTIONS), optionOverrides);
  number = number || 0;

  if (isNaN(number)) {
    return number;
  }

  if (options.scale) {
    // Number becomes a string
    number = Number(number).toFixed(options.scale);
  }

  number = number.toString();

  // Operations on string value

  if (options.separator) {
    number = number.replace(SEPARATOR_REGEX, options.separator);
  }

  return number;
}
