Skip to content

Instantly share code, notes, and snippets.

@anthonyquizon
Last active September 23, 2024 23:40
Show Gist options
  • Save anthonyquizon/b2398e3407798aa6f35c9b0c76b7b6c5 to your computer and use it in GitHub Desktop.
Save anthonyquizon/b2398e3407798aa6f35c9b0c76b7b6c5 to your computer and use it in GitHub Desktop.
BQN String interpolation
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
"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
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