Brad
Brad

Reputation: 9223

coffeescript: can this be rewritten to be more concise?

I have a snippet that prints the lowest number that is cleanly divisible in the numbers array.

numbers = [1, 2, 3, 4, 5, 6]

divisible = (large, small) -> large % small is 0

for i in [1..100]
    div = (divisible i, num for num in numbers)
    if (div.reduce (x, y) -> x and y)
        console.log i
        break

I'm new to coffeescript and I wanted to know if there's a more concise/cleaner implementation for this.

Upvotes: 0

Views: 53

Answers (2)

metalim
metalim

Reputation: 1613

Assuming there's no 0 in numbers.

gcd = ( a, b )->
    unless b then a else gcd b, a % b

lcm = ( a, b )->
    a * ( b / gcd a, b )

numbers = [ 2, 3, 4, 5, 6, 13, 98751 ]

console.log numbers.reduce lcm

Upvotes: 1

user619271
user619271

Reputation: 5012

I'd write something like this but it's about using Array.filter instead of Array.reduce, not about coffeescript tricks to make the original code smaller.

fn = (numbers) ->
  for i in [1..1000]
    return i if (numbers.filter (el) -> i % el == 0).length is numbers.length

console.log fn([1, 2, 3, 4, 5, 6])

Upvotes: 1

Related Questions