Created
May 30, 2016 12:05
-
-
Save kolo/d13871c59ea15b49dab02f78e117b936 to your computer and use it in GitHub Desktop.
"Functional" approach to solve diamond kata
This file contains hidden or 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
class Diamond | |
STARTING_CHARACTER = "A" | |
def initialize(letter) | |
@letter = letter | |
end | |
def to_s | |
lines.join("\n") | |
end | |
private | |
attr_reader :letter | |
def lines | |
go = ->(t, ch) { | |
t = t.push(spacify(line, ch)).unshift(spacify(line, ch)) | |
if ch == STARTING_CHARACTER | |
t | |
else | |
go[t, prec(ch)] | |
end | |
} | |
go[[spacify(line, letter)], prec(letter)] | |
end | |
def line | |
go = ->(str, ch) { | |
str = ch + str + ch | |
if ch == letter | |
str | |
else | |
go[str, ch.succ] | |
end | |
} | |
go[STARTING_CHARACTER, STARTING_CHARACTER.succ] | |
end | |
def spacify(str, ch) | |
str.gsub(/[^#{ch}]/, " ") | |
end | |
def prec(ch) | |
(ch.ord - 1).chr | |
end | |
end | |
puts Diamond.new("D") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment