Skip to content

Instantly share code, notes, and snippets.

@adeonhy
Last active December 13, 2017 14:11
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 adeonhy/e7e0cfde3537595dd3c6909555eda2f6 to your computer and use it in GitHub Desktop.
Save adeonhy/e7e0cfde3537595dd3c6909555eda2f6 to your computer and use it in GitHub Desktop.
'use strict'
const svg = (width, height, opts, f) => {
return tag('svg', Object.assign(
{},
{width: `${width}px`, height: `${height}px`},
opts
), f)
}
const translate = (x, y, contents) => tag('g', {transform: `translate(${x}, ${y})`}, contents)
const tag = (identifier, opts, contents) => {
let optAttr = Object.keys(opts).reduce((acc, key) => {
const val = opts[key]
return acc + ` ${key}="${val}"`
}, '')
if (contents == null) {
return `<${identifier}${optAttr} />`
} else {
return `<${identifier}${optAttr}>${_eval(contents)}</${identifier}>`
}
}
const t = tag
const _eval = contents => {
let contentsStr = ''
if (typeof(contents) === 'function') {
contentsStr = contents()
} else if (!contents) {
contentsStr = ''
} else if (Array.isArray(contents)) {
contentsStr = contents.reduce((acc, e) => {
return acc + _eval(e)
}, contentsStr)
} else {
contentsStr = String(contents)
}
return contentsStr
}
const kusaData = [
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4],
[0, 1, 2, 3, 4]
]
const growKusaCol = kusas => kusas.map(grow)
const grow = (kusa, offset) => {
const size = 10
const levelToColor = i => {
const colorTable = ['#eee', '#c6e48b', '#7bc96f', '#239a3b', '#196127']
return colorTable[i] || colorTable[0]
}
return t('rect', {x: 0, y: (size+2)*offset, width: size, height: size, fill: levelToColor(kusa)},'')
}
const kusaCols = kusaData.map((col, colIndex) => {
return translate(colIndex*13, 0, growKusaCol(col))
})
const svgString = svg(100, 100, null, kusaCols)
console.log(svgString)
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment