diff options
| author | mokha <mokha@cisco.com> | 2019-04-27 11:37:38 -0600 |
|---|---|---|
| committer | mokha <mokha@cisco.com> | 2019-04-27 11:37:38 -0600 |
| commit | 10e82cb9e1b9f5c9b3672b8c32bd6bc0473b37b0 (patch) | |
| tree | bb6e8d2d73884cae335278a733101ad2a35c4bee | |
| parent | bbb3fa3ac5ad2455aaccc73f2b91bddb61248212 (diff) | |
extract partition method
| -rw-r--r-- | spec/practice/luhn_spec.rb | 15 |
1 files changed, 7 insertions, 8 deletions
diff --git a/spec/practice/luhn_spec.rb b/spec/practice/luhn_spec.rb index ca1f373..964888b 100644 --- a/spec/practice/luhn_spec.rb +++ b/spec/practice/luhn_spec.rb @@ -25,16 +25,15 @@ require "spec_helper" class Luhn def self.valid?(credit_card) - x = credit_card.digits.each_with_index.inject(Hash.new { |hash, key| hash[key] = [] }) do |memo, (digit, index)| - index.even? ? memo[:odd].push(digit) : memo[:even].push(digit) + step_2, step_3 = partition(credit_card.digits) + (step_2.sum + step_3.map { |x| x * 2 }.map { |x| x.digits.sum }.sum).digits[0].zero? + end + + def self.partition(digits) + digits.each_with_index.inject([[], []]) do |memo, (digit, index)| + index.even? ? memo[0].push(digit) : memo[1].push(digit) memo end - step_2 = x[:odd].sum - step_3 = x[:even] - step_4 = step_3.map { |x| x * 2 } - step_5 = step_4.map { |x| x.digits.sum } - step_6 = step_5.sum - (step_2 + step_6).digits[0].zero? end end |
