Skip to content

Instantly share code, notes, and snippets.

@karolk
Last active February 15, 2017 00:00
Show Gist options
  • Save karolk/32751360b6615e61aa7b505a17294f20 to your computer and use it in GitHub Desktop.
Save karolk/32751360b6615e61aa7b505a17294f20 to your computer and use it in GitHub Desktop.
Diamond kata
// Simple use (from letter A, space as filler):
// diamond()("F")
// Specify beginning of alphabet and different filler character:
// diamond("F", "_")("K")
const diamond = (startChar="A", whiteSpace=" ") => {
const range = (from, to) => [from]
.concat(Array(to-from).fill(from))
.map((n,index) => n+index)
const codeToLetter = code => String.fromCharCode(code)
const prepareLine = (letter, index, {length}) => {
const line = whiteSpace.repeat(length * 2 - 1) // 2n - 1
return [line, letter]
}
const insertLetter = ([line, letter], index, {length}) => {
const lineArr = line.split('')
const midIndex = length - 1
lineArr.splice(midIndex - index, 1, letter)
lineArr.splice(midIndex + index, 1, letter)
return lineArr.join('')
}
return letter => {
const top = range(startChar.charCodeAt(0), letter.charCodeAt(0))
.map(codeToLetter)
.map(prepareLine)
.map(insertLetter)
const bottom = top.slice(0,-1).reverse()
return top.concat(bottom).join('\n')
}
}
const diamond = (startChar="A", whiteSpace=" ") => {
const range = (from, to) => [from]
.concat(Array(to-from).fill(from))
.map((n,index) => n+index)
const codeToLetter = code => String.fromCharCode(code)
const mirrorH = str => str.split('').reverse().join('')
const prepareLine = (letter, index, {length}) => {
const line = whiteSpace.repeat(length).split('')
line.splice(length - index - 1, 1, letter)
return line.join('')
}
return letter => {
const topLeftQuarter = range(startChar.charCodeAt(0), letter.charCodeAt(0))
.map(codeToLetter)
.map(prepareLine)
const top = topLeftQuarter.map(s => s + mirrorH(s).substr(1))
const bottom = top.slice(0, -1).reverse()
return top.concat(bottom).join('\n')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment