Sha256: 5997d0dc0e8d45a67fa60862b48b97afe5bbeecf20b7ee6263387cbb1928a161

Contents?: true

Size: 1.23 KB

Versions: 396

Compression:

Stored size: 1.23 KB

Contents

module.exports = class WordProblem

  BINARY_OPERATORS:
    'plus':          (l, r) -> l + r
    'minus':         (l, r) -> l - r
    'multiplied by': (l, r) -> l * r
    'divided by':    (l, r) -> l / r

  ERROR:
    tooComplicated: new Error("I don't understand the question")

  constructor: (@question = '') ->
    @matches = @question.match @pattern()

  operators: ->
    Object.keys @BINARY_OPERATORS

  pattern: ->
    operations = " (#{@operators().join('|')}) "

    /// (?:
      what[\x20]is[\x20] # what is
      ([-+]?[\d]+)       # +/- number
      #{operations}      # operator (plus, minus, etc.)
      ([-+]?[\d]+)       # +/- number
      (?:                # optional extra group
        #{operations}    # operator (plus, minus, etc.)
        ([-+]?[\d]+)     # +/- number
      )?                 # end optional extra group
    ) ///i

  tooComplicated: -> not @matches

  answer: =>
    throw @ERROR.tooComplicated if @tooComplicated()
    @evaluate()

  evaluate: ->
    out = 0
    m   = @matches

    out = @operate(m[2], m[1], m[3]) if m[1]? && m[2]? && m[3]?
    out = @operate(m[4], out,  m[5]) if m[4]? && m[5]?
    out

  operate: (operation, l, r) ->
    fn = @BINARY_OPERATORS[operation] || -> 0
    fn Number(l), Number(r)

Version data entries

396 entries across 396 versions & 1 rubygems

Version Path
trackler-2.2.1.180 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.179 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.178 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.177 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.176 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.175 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.174 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.173 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.172 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.171 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.170 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.169 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.167 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.166 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.165 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.164 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.163 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.162 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.161 tracks/coffeescript/exercises/wordy/example.coffee
trackler-2.2.1.160 tracks/coffeescript/exercises/wordy/example.coffee