Advertisement
Guest User

Untitled

a guest
Sep 22nd, 2019
168
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. /**
  2. * I like how languages such as Ruby and Python make it easy to iterate over
  3. * their respective number primitives, e.g. the "Rails way":
  4. *
  5. * 10.times do |x|
  6. * doSomething(x)
  7. * end
  8. *
  9. * In short, the above code is ~elegant~ in that when read in english, it's
  10. * pretty straightforward compared to a for loop. It's also
  11. * elegant in the regard that it's simplistic and concise.
  12. *
  13. * I think Javascript should have these kinds constructs. To that end, this is more
  14. * of an exercise of how we can use this kind of elegant feature.
  15. */
  16.  
  17. Number.prototype[Symbol.iterator] = function() {
  18. let current = 0
  19. return {
  20. next: () => {
  21. const increment = this > 0 ? 1 : -1
  22. return {
  23. done: current == this,
  24. value: current += increment
  25. }
  26. }
  27. }
  28. }
  29.  
  30. // now we can do a multiply function without the * or / operators using a similar construct
  31. function multiply(a, b) {
  32. return [...a].reduce(agg => a < 0 ? agg - b : agg + b, 0)
  33. }
  34.  
  35. console.log(multiply(10, 10)) // 100
  36. console.log(multiply(123, 0)) // 0
  37. console.log(multiply(3, 5)) // 15
  38. console.log(multiply(5, 3)) // 15
  39. console.log(multiply(-4, 5)) // -20
  40. console.log(multiply(4, -4)) // -16
  41. console.log(multiply(-7, -7)) // 49
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement