Fizz Buzz Kata

Episode #245 | 16 minutes | published on 11/24/2016 | Uses guard-2.14, swift-3.0
Subscribers Only
Code Katas are interesting challenges that can help you practice programming. Some are extremely difficult and others are fairly easy, but they all allow us to exercise the act of programming. Doing code katas can help you learn a new programming language, a new algorithm, or a new style of programming.In this episode we’ll tackle one of the most trivial katas: FizzBuzz.

Episode Links

  • CodeKata - You can find more information on what a Kata is and why it is useful, along with a list of example Kata challenges.
  • Kata Catalogue - A great list of code katas
  • Source Code

Atom

In this screencast I'm using Atom. I've installed the following packages:

  • language-swift (for syntax highlighting)
  • seti-icons (for the nicer file icons)
  • ex-mode and vim-mode (for vim-style editing)
  • symbol-gen (for fuzzy finding based on code symbols in your project)

Setting up

Let's first create the project.

mkdir ~/Desktop/Katas
cd ~/Desktop/Katas

Then we will jump into this directory to create our project structure with swift package manager.

swift package init

This creates our initial project structure, complete with tests. We can verify that this is all working by running the tests:

swift test

Next, we want to use guard to be able to run our tests with guard any time a file is modified. We'll first set up our Gemfile and add our gems to it:

bundle init
vim Gemfile
source 'https://rubygems.org'

gem 'colored'
gem 'guard-shell'

Here we're using the colored gem to provide quick & easy colored terminal output. We're also using a guard plugin, guard-shell to have guard just run a shell script when a file is changed. This will pull in guard as well.

To set up guard we need a Guardfile:

bundle install
bundle exec guard init

Then we can edit it to include our configuration:

require 'colored'

guard :shell do
  watch(/(.*).swift$/) {|m|

    puts "Modified: #{m[0]}"
    puts "Running tests..."
    `swift test`
    if $? == 0
      puts "Passed".green
    else
      puts "Failed".red
    end
  }
end

Lastly, we just need to start guard to have it watch our filesystem:

bundle exec guard

Now when we modify the swift source files or tests, guard will pick up the change and execute the block above, effectively running our tests.

blog comments powered by Disqus