Skip to content

Instantly share code, notes, and snippets.

@lokedhs
Last active October 13, 2020 15:31
Show Gist options
  • Save lokedhs/04af8aea0769f9f9abb8ef2a779233e3 to your computer and use it in GitHub Desktop.
Save lokedhs/04af8aea0769f9f9abb8ef2a779233e3 to your computer and use it in GitHub Desktop.
∇ wrapBox (v) {
w ← (⍴v)[1]
{((⊂"┏") , (w ⍴ ⊂"━") , ⊂"┓"),[0]⍵,[0](⊂"┗") , (w ⍴ ⊂"━") , ⊂"┛"} (⊂"┃") , v , ⊂"┃"
}
∇ render2d (v) {
w ← ((⍴v) ⍴ ⌈/[0] {(⍴⍵)[1]}¨v) {((↑⍴⍵) (⍺-(⍴⍵)[1]) ⍴ (⊂" ")),⍵}¨ v
wrapBox ⊃ ,[0]/ {⍺,(⊂" "),⍵}/ (⍉ (⍴w) ⍴ ⌈/[1] {↑⍴⍵}¨w) {⍵ ,[0] ((⍺-↑⍴⍵) ((⍴⍵)[1])) ⍴ (⊂" ")}¨w
}
Commented version:
∇ wrapBoxX (strlist) {
w ← (⍴ strlist)[1]
top ← (⊂"┏") , (w ⍴ ⊂"━") , ⊂"┓"
bottom ← (⊂"┗") , (w ⍴ ⊂"━") , ⊂"┛"
{top,[0]⍵,[0]bottom} (⊂"┃") , strlist , ⊂"┃"
}
∇ render2d (v) {
v ← v
⍝ The width of each column is the maximum width of any cell
colWidths ← ⌈/[0] {(⍴⍵)[1]}¨v
⍝ Pad each cell to the correct width
xAligned ← ((⍴v) ⍴ colWidths) {((↑⍴⍵) (⍺-(⍴⍵)[1]) ⍴ (⊂" ")),⍵}¨ v
⍝ Compute the height of each row in a similar way as the cols
colHeights ← ⌈/[1] {↑⍴⍵}¨xAligned
⍝ Pad each row so that they are all the same height
yAligned ← (⍉ (⍴ xAligned) ⍴ colHeights) {⍵ ,[0] ((⍺-↑⍴⍵) ((⍴⍵)[1])) ⍴ (⊂" ")}¨ xAligned
⍝ Add a space between cells on each row
vSeparated ← {⍺,(⊂" "),⍵}/ yAligned
wrapBox ⊃ ,[0]/ vSeparated
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment