Last active
September 23, 2024 23:40
-
-
Save anthonyquizon/b2398e3407798aa6f35c9b0c76b7b6c5 to your computer and use it in GitHub Desktop.
BQN String interpolation
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
string ← •Import "string.bqn" | |
# Poor mans templating engine | |
Fmt←{ 𝕨⊸string.Fmt¨<˘𝕩} | |
foo←∾∾⟨ | |
"<div>" | |
"<span>{value}</span>" Fmt ↕10 | |
"<span class='{0}'>{1}</span>" Fmt [⟨"foo",1⟩,⟨"bar",2⟩] | |
"</div>" | |
⟩ | |
•Show foo |
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
"Hello {foo} {bar}!" Fmt {foo⇐"formatted" ⋄ bar⇐"world"} # using namespaces | |
"Hello {} {}!" Fmt "formatted"‿"world" # using lists | |
"Hello {}!" Fmt "formatted"‿"world" # extra list values are dropped off | |
"Hello {foo} {bar}!" Fmt "formatted"‿"world" # lists can still use named templates and will replace in order |
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
Fmt ⇐ { | |
ch 𝕊 d: 6≡•Type 𝕩 ? # named replacement values | |
s‿e←ch⊸=¨"{}" ⋄ f←(+`s+»e)⊸⊔ch # fragments | |
m←f∊t←{'{'∾𝕩∾'}'}¨k←•ns.Keys d # k: keys, t: tags | |
v←(m/t⊐f)⊸⊏ (d •ns.Get¨k) # v: replacement values | |
∾v⌾(m⊸/) f | |
; ch 𝕊 𝕩: # unnamed replacement values | |
s‿e←ch⊸=¨"{}" ⋄ f←(+`s+»e)⊸⊔ch # fragments | |
m←∾('}'=¯1↑¨f)∧'{'=1↑¨f | |
t←m/f # tags | |
v←(≠t)𝕩∾⟨⟩¨↕0⌈(≠t)-(≠𝕩) # replacement values | |
∾v⌾(m⊸/)f | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment