user3714522
user3714522

Reputation: 1

Coffeescript: return true or false in one-liner

For an example function like:

singleDigits = (list) ->
    return false for i in list when i > 9
    true

I'm wondering whether or not that would be possible without the lone trueat the end
e.g.

singleDigits = (list) -> return true unless false for i in list when i > 9

(I know that is not working, just to illustrate what I'm asking)

Upvotes: 0

Views: 563

Answers (2)

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78629

I think you could use the some method in Array.

someDigits = (list) -> list.some (digit) -> digit > 9

The advantage over reduce is that it will stop in the moment the predicate becomes true, whereas reduce will still finish going over the entire array.

See Array.prototype.some reference.

Upvotes: 3

phenomnomnominal
phenomnomnominal

Reputation: 5515

How about:

singleDigits = (list) ->
    list.reduce (previous = true, next) -> previous and next < 10

Upvotes: 0

Related Questions