Last active
April 8, 2019 07:01
-
-
Save rix1/0ca397e6fe3ff78b5955f14f135a95c6 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
Introducing `f` – a simple formatter for complex strings | |
optimized for readability, inspired by Python's printf | |
✅ No need for new variable names | |
✅ Readable code | |
✅ Readable result string | |
*/ | |
// Usage | |
pf`{paneler blir montert} {i uke} {21} ({26.} - {31. Oct})`( | |
prefix, | |
intl.formatMessage(m.installationDateInWeek), | |
_startDate.week(), | |
startOfWeek.format("Do"), | |
endOfWeek.format("Do MMMM") | |
); | |
// Implementation | |
const f = ([str] = fistArg) => (...args) => { | |
let counter = 0; | |
const s = str.replace(/(\{[a-z\d\s\.]+\})/gi, () => { | |
return args[counter++] || ""; | |
}); | |
}; | |
// Alternative approaches | |
/* | |
Template literal approach: | |
✅ No new variables | |
❌ Readable code | |
❌ Readable result string | |
*/ | |
const inline = `${prefix} ${intl.formatMessage( | |
m.installationDateInWeek | |
)} ${_startDate.week()} (${startOfWeekStartDate.format("Do")} – | |
${endOfWorkWeekEndDate.format("Do MMMM")})`; | |
/* | |
2001 approach: | |
✅ No new variables | |
✅ Readable code | |
❌ Readable result string | |
*/ | |
const inline = | |
prefix + | |
" " + | |
intl.formatMessage(m.installationDateInWeek) + | |
" " + | |
_startDate.week() + | |
" (" + | |
startOfWeekStartDate.format("Do") + | |
" – " + | |
endOfWorkWeekEndDate.format("Do MMMM") + | |
")"; | |
/* | |
Alternative approach with variables | |
❌ Have to come up with new variable names | |
✅ Readable code | |
✅ Readable result string | |
*/ | |
const installationDateInWeek = intl.formatMessage(m.installationDateInWeek); | |
const startWeek = _startDate.week(); | |
const startDate = startOfWeekStartDate.format("Do"); | |
const endDate = endOfWorkWeekEndDate.format("Do MMMM"); | |
const inline = `${prefix} ${installationDateInWeek} ${startDate} – ${endDate})`; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment