Last active
November 21, 2020 19:59
-
-
Save karol-majewski/d7b429f1349c614626f79e2d4c66f636 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface Milestone { | |
label: string; | |
count: number; | |
} | |
interface Options { | |
separator?: string; | |
} | |
const format = (milestones: Milestone[], options: Options = { separator: ' ' }): string => | |
milestones | |
.filter(({ count }) => count > 0) | |
.map(({ count, label }) => `${count} ${label}`) | |
.join(options.separator) | |
console.log( | |
format([ | |
{ label: 'years', count: 1 }, | |
{ label: 'months', count: 2 }, | |
{ label: 'days', count: 32 }, | |
{ label: 'seconds', count: 2 }, | |
]) | |
) |
Original design:
function parseDate(input: number[]) {
const [years, months, days] = input;
return ([
...years ? [`${years} years`]: [],
...months ? [`${months} months`]: [],
...days ? [`${days} days`]: [],
]).join(' ')
};
- Unsafe array destructuring (the tuple must have 3 elements, it's not any array)
- Ambiguity: should
0
be preserved? Implicit coercion eats zeros (they're falsy) - Relies on a... clever solution (desctructuring
[]
returns nothing) - The default separator is baked in
- Allows invalid values (80 seconds, 14 months)
interface Milestone {
label: React.ReactElement | ((count: number) => React.ReactElement);
count: number;
}
const format = (milestones: Milestone[], separator: string = ' '): string =>
milestones
.filter(({ count }) => count > 0)
.map(({ count, label }) =>
React.isValidElement(label)
? label
: label(count)
)
.join(separator);
const milestones: Milestone[] = [
{ count: 20, label: count => t('app:milestone.year', { count })},
{ count: 10, label: count => t('app:milestone.month', { count })},
{ count: 12, label: count => t('app:milestone.day', { count })},
{ count: 42, label: count => t('app:milestone.second', { count })},
]
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improved design: