# MichaelBaker/katas

Adds some other katas I've tried

MichaelBaker committed May 6, 2012
1 parent cc020f9 commit e608d56b3acb805111488f19ae734835b94e4d4f
 @@ -0,0 +1,19 @@ +class Integer + def prime_factors + x = self + divisor = 2 + primes = [] + limit = Math.sqrt x + while x >= 2 + if x % divisor == 0 + primes << divisor + x = x / divisor + elsif divisor > limit + divisor = x + else + divisor = divisor + 1 + end + end + primes + end +end
 @@ -0,0 +1,23 @@ +require 'minitest/autorun' +require './primes' + +class PrimesTest < MiniTest::Unit::TestCase + def self.test_cases + [[0, []], + [1, []], + [2, [2]], + [3, [3]], + [4, [2, 2]], + [5, [5]], + [7, [7]], + [8, [2, 2, 2]], + [9, [3, 3]], + [10, [2, 5]]] + end + + test_cases.each do |number, primes| + define_method "test_#{number}" do + assert_equal(primes, number.prime_factors) + end + end +end
 @@ -0,0 +1,4 @@ +watch ".*" do |file| + system "clear" + system "ruby primes_spec.rb" +end
 @@ -0,0 +1,4 @@ +watch ".*" do |filename| + system "clear" + system "rspec -fdocumentation string_calculator_spec.rb" +end
 @@ -0,0 +1,47 @@ +module StringCalculator + DEFAULT_SEPARATOR = /,|\s/ + MULTI_CHARACTER_SEPARATOR = /\[(.*?)\]/ + CUSTOM_SEPARATOR_LINE = /^\/\/(.*)\n/ + VALID_NUMBERS = lambda { |number| 0 <= number && number <= 1000 } + + def self.add(string) + numbers = string_to_list string + assert_no_negative_numbers numbers + numbers.select(&VALID_NUMBERS).reduce &:+ + end + + private + + def self.string_to_list(string) + return [0] if string.empty? + string, separator = parse_string_with_separator(string) if contains_custom_separator? string + string.split(separator || DEFAULT_SEPARATOR).map &:to_i + end + + def self.assert_no_negative_numbers(numbers) + negative_numbers = numbers.select { |number| number < 0 } + if negative_numbers.any? + raise "Negatives not allowed: #{negative_numbers.join(', ')}" + end + end + + def self.parse_string_with_separator(string) + separator = parse_separator string[CUSTOM_SEPARATOR_LINE] + [string.sub(CUSTOM_SEPARATOR_LINE, ""), separator] + end + + def self.parse_separator(line) + if line =~ MULTI_CHARACTER_SEPARATOR + Regexp.new line.scan(MULTI_CHARACTER_SEPARATOR) + .flatten + .map {|separator| Regexp.escape separator} + .join("|") + else + line[2] + end + end + + def self.contains_custom_separator?(string) + string.start_with? "//" + end +end