Take the 2-minute tour ×

I'd like to write some code that easily handles the input to be either a single value or an array and perform an operation on either the single value or each value in the array.

Ideally the code would just look like:

a = for i in j()

but j could return either 1 or [1, 2, 3].

I don't even see a good way to somehow check to see if j returns an array. Maybe coffeescript has some good type identification system so I could do

if j().isArray then j() else [j()] 

or something?

Anyone know of a syntactically appealing way of hiding this array conversion logic as much as possible?

share|improve this question
You should cache j() in a var. –  user142019 Dec 9 '11 at 7:23
what does that get me? –  xaxxon Dec 9 '11 at 7:23
It looks like jQuery has an isArray method I could potentially use. In this case that would be fine, but I'd prefer an answer that doesn't use jquery –  xaxxon Dec 9 '11 at 7:27
better performance. –  user142019 Dec 9 '11 at 14:31
@WTP that's generally good advice, but coffeescript takes care of that for you, j() won't be called multiple times. –  Ricardo Tomasi Dec 9 '11 at 21:44

2 Answers 2

up vote 8 down vote accepted
[].concat j()

will copy the result if array, wrap otherwise.

share|improve this answer
asArray = (j) -> if j instanceof Array then j else [j]

Then call as

a = for i in asArray(j())
share|improve this answer
yeah, seems like that's about what I'm going to have to do. –  xaxxon Dec 9 '11 at 7:41
instanceof does have some gotchas you should be aware of: perfectionkills.com/…. If you need to, use the alternate isArray definition at the bottom of that page. –  user24359 Dec 9 '11 at 7:49
yeah, I'll probably use jquery's $.isArray: api.jquery.com/jQuery.isArray –  xaxxon Dec 9 '11 at 7:53

Your Answer


