"use strict";

var nunjucks = require('nunjucks');
var utils = require('./utils');
var _ = require('lodash');

nunjucks.env = new nunjucks.Environment();

var basicFormatter = new Intl.NumberFormat('en');

var specificFormatter = function(sigFig) {
    return new Intl.NumberFormat('en',{minimumFractionDigits: sigFig});
};

var cachedFormatters = _.memoize(specificFormatter);

nunjucks.env.addFilter('toLocaleString', function(val, n) {
    if (val===undefined || isNaN(val)) {
        return val;
    }

    if (n) {
        return cachedFormatters(n).format(val);
    } else {
        return basicFormatter.format(val);
    }
});

nunjucks.env.addFilter('filterNoData', utils.filterNoData);

nunjucks.env.addFilter('toFriendlyDate', function(date) {
    return new Date(date).toLocaleString();
});


"use strict";

var nunjucks = require('nunjucks');
var utils = require('./utils');
var _ = require('lodash');

nunjucks.env = new nunjucks.Environment();

if (window.hasOwnProperty('Intl')) {
    // Intl is available, we should use the faster NumberFormat
    var basicFormatter = new Intl.NumberFormat('en'),
        minDigitFormatter = function(n) {
            return new Intl.NumberFormat('en', { minimumFractionDigits: n });
        },
        cachedMinDigitFormatter = _.memoize(minDigitFormatter);

    var toLocaleStringFormatter = function(val, n) {
        if (val === undefined || isNaN(val)) {
            return val;
        }

        if (n) {
            return cachedMinDigitFormatter(n).format(val);
        } else {
            return basicFormatter.format(val);
        }
    };
} else {
    // Intl is not available, we should use the more compatible toLocaleString
    var toLocaleStringFormatter = function(val, n) {
        if (val === undefined || isNaN(val)) {
            return val;
        }

        if (n) {
            return val.toLocaleString('en', { minimumFractionDigits: n });
        } else {
            return val.toLocaleString('en');
        }
    };
}

nunjucks.env.addFilter('toLocaleString', toLocaleStringFormatter);

nunjucks.env.addFilter('filterNoData', utils.filterNoData);

nunjucks.env.addFilter('toFriendlyDate', function(date) {
    return new Date(date).toLocaleString();
});

Support older browsers that lack Intl
Support older browsers that lack Intl

While Intl.NumberFormat is a much more performant implementation
(see #1566), and is supported by all modern browsers, there are
still older browsers in the wild that lack support for it. Most
notably, Safari 9 and the Android built-in browser do not support
it, leaving many users stuck on older iPads and Macs unable to
access the site.

By checking for Intl support before using it, we ensure backwards
compatibility, while also using the more performant modern options
wherever available.

Refs #1804 :bug: :apple: :globe_with_meridians:
