Skip to content
This repository has been archived by the owner on Nov 8, 2020. It is now read-only.

Commit

Permalink
Fix formatter to correctly preserve unidentified values and not greed…
Browse files Browse the repository at this point in the history
…ily format
  • Loading branch information
Samrith Shankar committed Jul 4, 2019
1 parent 8abe454 commit 0172998
Showing 1 changed file with 16 additions and 5 deletions.
21 changes: 16 additions & 5 deletions src/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,25 @@ export default function Formatter(
): string {
const { months, days, meridians } = locale;
const date: Date = new Date(dateValue);
const regexp: RegExp = /(M+)|(Y+)|(D+)|(d+)|(h+)|(m+)|(s+)|(a+)|(A+)/g;
const regexp: RegExp = /(Y+)|(M+)|(D+)|(d+)|(h+)|(m+)|(s+)|(a+)|(A+)/g;
const replaceKeys = replacer(date, months, days, meridians);
const matches = format.match(regexp) || [];

return matches.reduce(
(value, key) => value.replace(key, replaceKeys(key)),
format
const replaced: Object = {};

const deducedFormat = matches
.reduce((acc, key, index) => {
replaced[acc.indexOf(key) + index] = replaceKeys(key);
return acc.replace(key, '');
}, format)
.split('');

Object.entries(replaced).forEach(
([index, value]): void => {
deducedFormat.splice(parseInt(index, 10), 0, value);
}
);

return deducedFormat.join('');
}

function replacer(
Expand Down

0 comments on commit 0172998

Please sign in to comment.