Skip to content

Commit c5fa5ee

Browse files
Merge pull request #299 from Marianna-K/master
simplified ordinalDate filter
2 parents a5e1a86 + b3e7dd4 commit c5fa5ee

File tree

1 file changed

+5
-46
lines changed

1 file changed

+5
-46
lines changed

src/filters/ordinalDate/ordinalDate.js

Lines changed: 5 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -5,59 +5,18 @@ angular.module( 'angularUtils.filters.ordinalDate', [] )
55
var getOrdinalSuffix = function(number) {
66
var suffixes = ["'th'", "'st'", "'nd'", "'rd'"];
77
var relevantDigits = (number < 30) ? number % 20 : number % 30;
8-
return (relevantDigits <= 3) ? suffixes[relevantDigits] : suffixes[0];
9-
};
10-
11-
/**
12-
* Look through the format string for any possible match for 'd'.
13-
* It needs to ignore 'dd' and also occurrences of the letter d inside
14-
* string such as "d 'day of' MM'.
15-
* @param format
16-
*/
17-
var getIndecesOfDayCharacter = function(format) {
18-
var dayRegex = /(?:'(?:[^']|'')*')|(?:d+)/g;
19-
var matchingIndices = [];
20-
var finishedLooking = false;
21-
22-
while(!finishedLooking) {
23-
var matches = dayRegex.exec(format);
24-
if (matches) {
25-
dayRegex.lastIndex = matches.index + matches[0].length;
26-
if (matches[0] === 'd') {
27-
matchingIndices.push(matches.index + 1);
28-
}
29-
} else {
30-
finishedLooking = true;
31-
}
32-
}
33-
34-
return matchingIndices;
35-
};
36-
37-
/**
38-
* Insert a string at a given index of another string
39-
* @param inputString
40-
* @param index
41-
* @param stringToInsert
42-
* @returns {string}
43-
*/
44-
var insertAtIndex = function(inputString, index, stringToInsert) {
45-
var partBeforeIndex = inputString.substring(0, index);
46-
var partAfterIndex = inputString.substring(index, inputString.length);
47-
return partBeforeIndex + stringToInsert + partAfterIndex;
8+
return "d" + ((relevantDigits <= 3) ? suffixes[relevantDigits] : suffixes[0]);
489
};
4910

5011
return function(timestamp, format) {
12+
var regex = /d+((?!\w*(?=')))|d$/g;
5113
var date = new Date(timestamp);
5214
var dayOfMonth = date.getDate();
5315
var suffix = getOrdinalSuffix(dayOfMonth);
5416

55-
var matchingIndices = getIndecesOfDayCharacter(format);
56-
57-
// now we to insert the suffix at the index(-ces) that we found
58-
for (var i = matchingIndices.length; i > 0; i --) {
59-
format = insertAtIndex(format, matchingIndices[i-1], suffix);
60-
}
17+
format = format.replace(regex, (match) => {
18+
return match === "d" ? suffix : match;
19+
});
6120
return $filter('date')(date, format);
6221
};
6322
}]);

0 commit comments

Comments
 (0)