fix count escape (#17841)

This commit is contained in:
zombieJ 2019-07-24 15:07:10 +08:00 committed by GitHub
parent d4164f6c33
commit bce3696ec0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 3 deletions

View File

@ -3,6 +3,7 @@ import MockDate from 'mockdate';
import moment from 'moment';
import { mount } from 'enzyme';
import Statistic from '..';
import { formatTimeStr } from '../utils';
const delay = timeout => new Promise(resolve => setTimeout(resolve, timeout));
@ -104,4 +105,10 @@ describe('Statistic', () => {
});
});
});
describe('utils', () => {
it('format should support escape', () => {
expect(formatTimeStr(1000 * 60 * 60 * 24, 'D [Day]')).toBe('1 Day');
});
});
});

View File

@ -35,10 +35,14 @@ const timeUnits: [string, number][] = [
['S', 1], // million seconds
];
function formatTimeStr(duration: number, format: string) {
export function formatTimeStr(duration: number, format: string) {
let leftDuration: number = duration;
return timeUnits.reduce((current, [name, unit]) => {
const escapeRegex = /\[[^\]]*\]/g;
const keepList: string[] = (format.match(escapeRegex) || []).map(str => str.slice(1, -1));
const templateText = format.replace(escapeRegex, '[]');
const replacedText = timeUnits.reduce((current, [name, unit]) => {
if (current.indexOf(name) !== -1) {
const value = Math.floor(leftDuration / unit);
leftDuration -= value * unit;
@ -48,7 +52,14 @@ function formatTimeStr(duration: number, format: string) {
});
}
return current;
}, format);
}, templateText);
let index = 0;
return replacedText.replace(escapeRegex, () => {
const match = keepList[index];
index += 1;
return match;
});
}
export function formatCountdown(value: countdownValueType, config: CountdownFormatConfig) {