Skip to content

Instantly share code, notes, and snippets.

@hugecannon
Created August 3, 2012 09:20
Show Gist options
  • Save hugecannon/3246228 to your computer and use it in GitHub Desktop.
Save hugecannon/3246228 to your computer and use it in GitHub Desktop.
if (a OR b OR c)
if a
end if
if b
end if
if c
end if
[code]
[code]
[code]
end if
@jbrunton
Copy link

jbrunton commented Aug 3, 2012

Depending on the capabilities of the language, it might be neat to separate out the things you want to test against and the code you'd execute if they're true, from the code which actually invokes the tests and executes the code blocks (though there's not much payoff if you just have a few predicates).

# clearly write out all the tests and corresponding code blocks, but don't execute anything yet.
things_to_test = [
    { test: a, do: [code] },
    { test: b, do: [code] },
    { test: c, do: [code] }
]

# do the tests in one line
if _.any things_to_test, ( thing ) -> thing.test
    # execute the relevant code blocks in one line
    _.each things_to_test, ( thing ) -> if thing.test then thing.do()    
    # rest of code goes here

@jbrunton
Copy link

jbrunton commented Aug 3, 2012

NB that's in coffeescript, using underscore.js.

@zofrex
Copy link

zofrex commented Aug 3, 2012

My take in Ruby:

class Switch
  def initialize item, &block
    @item = item
    @match = false
    instance_eval &block
    if @match && !@match_block.nil?
      instance_eval &@match_block
    end
  end

  def eq comparator, &block
    if @item == comparator
      instance_eval &block
      @match = true
    end
  end

  def match &block
    @match_block = block
  end
end

def switch item, &block
  Switch.new item, &block
end

test = "a"

switch test do
  eq "a" do
    puts "A"
  end

  eq "b" do
    puts "B"
  end

  match do
    puts "run if either matches"
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment