简体   繁体   中英

How to convert this function from Ruby to JavaScript so it will look the same

I wrote a simple function in Ruby that accepts a number and returns the sum of all multiples of 3 and 5 upto (and including) that number.

For example: findSum(5) returns 8 (because 3 + 5),

findSum(10) returns 33 (because 3 + 5 + 6 + 9 + 10).

findSum(15) returns 60 and so on:

def findSum(num)
  (1..num).select { |n| n % 3 == 0 || n % 5 == 0 }.reduce { |sum, n| sum += n }
end

Do you have any idea how to "copy" and "convert" that Ruby function into a JavaScript function so it will LOOK almost the same?

I know JavaScript can solve it in many different ways, but for now as a beginner I may NOT understand most of them anyway, I just need to see the most similar way of coding that same function above in JavaScript.

There isn't as nice a way to make a range of numbers from 1 to n, but here's one option:

Array.from({ length: num }, (_, i) => i + 1)

After that, instead of .select you'll use .filter , and then .reduce exists in both languages.

 function findSum(num) { return Array.from({ length: num }, (_, i) => i + 1) .filter(n => n % 3 === 0 || n % 5 === 0) .reduce((sum, n) => sum += n) } console.log(findSum(5)) console.log(findSum(10)) console.log(findSum(15))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM