Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * I like how languages such as Ruby and Python make it easy to iterate over
- * their respective number primitives, e.g. the "Rails way":
- *
- * 10.times do |x|
- * doSomething(x)
- * end
- *
- * In short, the above code is ~elegant~ in that when read in english, it's
- * pretty straightforward compared to a for loop. It's also
- * elegant in the regard that it's simplistic and concise.
- *
- * I think Javascript should have these kinds constructs. To that end, this is more
- * of an exercise of how we can use this kind of elegant feature.
- */
- Number.prototype[Symbol.iterator] = function() {
- let current = 0
- return {
- next: () => {
- const increment = this > 0 ? 1 : -1
- return {
- done: current == this,
- value: current += increment
- }
- }
- }
- }
- // now we can do a multiply function without the * or / operators using a similar construct
- function multiply(a, b) {
- return [...a].reduce(agg => a < 0 ? agg - b : agg + b, 0)
- }
- console.log(multiply(10, 10)) // 100
- console.log(multiply(123, 0)) // 0
- console.log(multiply(3, 5)) // 15
- console.log(multiply(5, 3)) // 15
- console.log(multiply(-4, 5)) // -20
- console.log(multiply(4, -4)) // -16
- console.log(multiply(-7, -7)) // 49
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement