开发者

Should I use CoffeeScript soaks and the existential operator together?

I'm working on a script that accepts a settings object, but uses default values where settings are not provided.

I just wrote the following line of CoffeeScript:

iframe_width = settings?.iframe?.width? ? $iframe_body.width()

My intent, in plain English, is:

If the settings object is defined, and it defines a property iframe, and the iframe property defines a property width, then assign the value of the latter property to the variable iframe_width. Otherwise, assign the value returned by calling $iframe_body.width().

Does my CoffeeScript code reflect my intent, and is it the most effective way to express that? It seems awkward with all of the existential operators (?), so I wanted to put it out there for some feedback (the compiled JavaScript is very terse and cryptic, so it's hard to tell if should work as intended).

Also, I'm not sure whether there's any redundancy in using both the standard existential operator (?) and its accessor variant (?.) together.

Thanks!


Update:

The code above doesn't seem to work as expected; however, this doe开发者_如何学Gos:

iframe_width = settings?.iframe?.width ? $iframe_body.width()

That makes sense, since I don't think the former code actually accesses the width property, but rather just checks for its existence (twice, even?). In this code, I removed the ? just after the width property, since I think that's redundant with the ? operator between the two expressions. Does that seem correct?


(Note: This answer was written before the question was updated. As the questioner realized, foo? ? bar isn't just redundant—it actually won't work, because foo? evaluates to true or false, and is therefore always non-null.)

You have two good options for simplifying this: One, you could replace the existential binary operator with an or:

iframe_width = settings?.iframe?.width? or $iframe_body.width()

Two, you could ditch the ? after width—it's redundant:

iframe_width = settings?.iframe?.width ? $iframe_body.width()

Now, you could do both if and only if iframe.width will never be 0 (since 0 or x is x). If you can be sure of that, go ahead and make it

iframe_width = settings?.iframe?.width or $iframe_body.width()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜