Skip to content

Instantly share code, notes, and snippets.

@JakeTheCorn
Created May 1, 2020 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JakeTheCorn/c96c4bf7a8d6e23c5a4c963b3e2d83d9 to your computer and use it in GitHub Desktop.
Save JakeTheCorn/c96c4bf7a8d6e23c5a4c963b3e2d83d9 to your computer and use it in GitHub Desktop.
lil Primitive ts code snippet display
// todo: write tests
interface SnippetProps {
val: string
}
export const Snippet = ({
val
}: SnippetProps): JSX.Element => {
const elements = []
const lines = val.split('\n')
for (var i = 0; i < lines.length; i++) {
const line = lines[i]
if (i === 0 && line === '') {
continue
}
let leadingSpaceCount = 0
for (var j = 0; j < line.length; j++) {
const char = line[j]
if (/\s/.test(char)) {
leadingSpaceCount++
continue
}
break
}
elements.push(
<span key={i}>
{space(leadingSpaceCount)}{line}
<br />
</span>
)
}
return (
<code>
{elements}
</code>
)
}
function space(n: number): JSX.Element {
return <>{Array(n).fill(<>&nbsp;</>)}</>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment