Last active
February 15, 2017 00:00
-
-
Save karolk/32751360b6615e61aa7b505a17294f20 to your computer and use it in GitHub Desktop.
Diamond kata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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') | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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