Skip to content

Instantly share code, notes, and snippets.

@marlun78
Created November 26, 2015 10:05
Show Gist options
  • Save marlun78/d72044017e0439494ce1 to your computer and use it in GitHub Desktop.
Save marlun78/d72044017e0439494ce1 to your computer and use it in GitHub Desktop.
var angular = require('angular');
module.exports = angular.module('models.Locale', [])
.value('Locale', Locale);
/**
* @typedef Locale
* @property {string} language
* @property {string|null} country
* @method {boolean} equals
* @method {string} toString
*/
/**
* Locale Class
* @constructor
* @param {string} language - A two-letter ISO 639-1 language code
* @param {string} [country=null] - A two-letter ISO 3166-1 alpha-2 country code
* @returns {Locale} An immutable locale object
*/
function Locale(language, country) {
if (!_.isString(language) || language.length !== 2) {
throw new TypeError('Language parameter must be a two-letter ISO 639-1 language code');
} else {
this.language = language.toLowerCase();
}
if (!_.isString(country)) {
this.country = null;
} else if (country.length !== 2) {
throw new Error('Country parameter is optional, but if specified, it must be a two-letter ISO 3166-1 alpha-2 country code');
} else {
this.country = country.toUpperCase();
}
Object.freeze(this);
}
/**
* Static property
*/
Object.defineProperties(Locale, {
SEPARATOR: {
get: function() {
return '-';
}
}
});
var localePattern = /^([a-zA-Z]{2})(?:[\-_]([a-zA-Z]{2})?)$/;
/**
* Parses a string and tries to create a new locale object from it.
* If parsing fails, it returns null.
* @static
* @param {string} stringLocale
* @returns {string|null}
*/
Locale.from = function(stringLocale) {
var locale = null;
if (_.isString(stringLocale)) {
var matches = localePattern.exec(stringLocale);
if (matches) {
// The matches looks something like this:
// ["en-US", "en", "US", index: 0, input: "en-US"]
locale = new Locale(matches[1], matches[2]);
}
}
return locale;
};
Locale.prototype = {
constructor: Locale,
/**
* Compares two locale objects with one another and returns true if they are alike.
* @param {Locale} otherLocale
* @returns {boolean}
*/
equals: function(otherLocale) {
return this.language === otherLocale.language && this.country === otherLocale.country;
},
/**
* Returns a string representation of the locale.
* @returns {string} - language[-COUNTRY] eg. `en` or `en-US`
*/
toString: function() {
if (this.country !== null) {
return this.language + Locale.SEPARATOR + this.country;
} else {
return this.language;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment