code_junkie

How much code do you tend to write before you test

Nov 13th, 2011
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. sum
  2. "sum up all elements.
  3. This is implemented using a variant of the normal inject:into: pattern.
  4. The reason for this is that it is not known whether we are dealing with number
  5. (i.e. if 0 is a good initial value for the sum).
  6. Consider a collection of measurement or physical objects, 0 would be the unitless
  7. value and would not be appropriate to add with the unit-ed objects."
  8.  
  9. | sum sample |
  10.  
  11. sample := self anElement.
  12. sum := self inject: sample into: [:accum :each | accum + each].
  13. ^ sum - sample.
  14.  
  15. "
  16. TestCase should: [ { } sum ] raise:Error.
  17. TestCase should: [ '' sum ] raise:Error.
  18.  
  19. TestCase assert: ( { 1 } sum = 1 ).
  20. TestCase assert: ( { 1. 2. 3. 4. } sum = 10 ).
  21. TestCase assert: ( (1 to:10) sum = 55 ).
  22. TestCase assert: ( 'abc' asByteArray sum = 294 ).
  23.  
  24. TestCase assert: ( { 10 +/- 2.
  25. 20 +/- 4.
  26. 100 +/- 10 } sum = (130 +/- 16) ).
  27.  
  28. TestCase assert: ( { (1 / 9).
  29. (1 / 7).
  30. } sum = (16 / 63) ).
  31. "
Add Comment
Please, Sign In to add comment