Permalink
Browse files

feat(dateparser): allow overriding of parsers

- Add ability to override parser

Closes #6370
Closes #6373
  • Loading branch information...
1 parent 4872c05 commit 5a3e44a146f81ee6d182e9e5f473a161050425bc @dougludlow dougludlow committed with wesleycho Dec 14, 2016
Showing with 42 additions and 1 deletion.
  1. +18 −1 src/dateparser/dateparser.js
  2. +24 −0 src/dateparser/test/dateparser.spec.js
@@ -1,6 +1,6 @@
angular.module('ui.bootstrap.dateparser', [])
-.service('uibDateParser', ['$log', '$locale', 'dateFilter', 'orderByFilter', function($log, $locale, dateFilter, orderByFilter) {
+.service('uibDateParser', ['$log', '$locale', 'dateFilter', 'orderByFilter', 'filterFilter', function($log, $locale, dateFilter, orderByFilter, filterFilter) {
// Pulled from https://github.com/mbostock/d3/blob/master/src/format/requote.js
var SPECIAL_CHARACTERS_REGEXP = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
@@ -243,6 +243,23 @@ angular.module('ui.bootstrap.dateparser', [])
this.init();
+ function getFormatCodeToRegex(key) {
+ return filterFilter(formatCodeToRegex, {key: key}, true)[0];
+ }
+
+ this.getParser = function (key) {
+ var f = getFormatCodeToRegex(key);
+ return f && f.apply || null;
+ };
+
+ this.overrideParser = function (key, parser) {
+ var f = getFormatCodeToRegex(key);
+ if (f && angular.isFunction(parser)) {
+ this.parsers = {};
+ f.apply = parser;
+ }
+ }.bind(this);
+
function createParser(format) {
var map = [], regex = format.split('');
@@ -791,4 +791,28 @@ describe('date parser', function() {
});
});
});
+
+ describe('overrideParser', function() {
+ var twoDigitYearParser = function (value) {
+ this.year = +value + (+value > 30 ? 1900 : 2000);
+ };
+
+ it('should get the current parser', function() {
+ expect(dateParser.getParser('yy')).toBeTruthy();
+ });
+
+ it('should override the parser', function() {
+ dateParser.overrideParser('yy', twoDigitYearParser);
+ expect(dateParser.parse('68', 'yy').getFullYear()).toEqual(1968);
+ expect(dateParser.parse('67', 'yy').getFullYear()).toEqual(1967);
+ expect(dateParser.parse('31', 'yy').getFullYear()).toEqual(1931);
+ expect(dateParser.parse('30', 'yy').getFullYear()).toEqual(2030);
+ });
+
+ it('should clear cached parsers', function() {
+ expect(dateParser.parse('68', 'yy').getFullYear()).toEqual(2068);
+ dateParser.overrideParser('yy', twoDigitYearParser);
+ expect(dateParser.parse('68', 'yy').getFullYear()).toEqual(1968);
+ });
+ });
});

0 comments on commit 5a3e44a

Please sign in to comment.