Permalink
Browse files

Use 'loop' for whiles that go on forever. Closes #35.

  • Loading branch information...
1 parent 01b9eca commit 591f3649311372df67da1720016baa588941c555 @rstacruz rstacruz committed Oct 20, 2011
Showing with 37 additions and 10 deletions.
  1. +7 −1 lib/helpers.coffee
  2. +13 −9 lib/js2coffee.coffee
  3. +11 −0 test/features/loop.coffee
  4. +6 −0 test/features/loop.js
View
@@ -76,6 +76,12 @@ unshift = (str) ->
return str if !m1 or !m2 or m1.length != m2.length
str = str.replace(/^ /gm, '')
+# `truthy()`
+# Tests if the given node is constantly truthy. Currently only works with
+# `true` and non-zero numbers.
+truthy = (n) ->
+ n.isA('true') or (n.isA('number') and parseFloat(n.src()) isnt 0.0)
+
# `strEscape()`
# Escapes a string.
# Example:
@@ -116,6 +122,6 @@ unreserve = (str) ->
@Js2coffeeHelpers = exports =
{Code, p, strEscape, unreserve, unshift, isSingleLine, trim,
- blockTrim, ltrim, rtrim, strRepeat, paren}
+ blockTrim, ltrim, rtrim, strRepeat, paren, truthy}
module.exports = exports if module?
View
@@ -19,10 +19,8 @@ _ = @_ or require('underscore')
{Types, Typenames, Node} = @NodeExt or require('./node_ext')
-{Code, p, strEscape, unreserve,
-unshift, isSingleLine,
-trim, blockTrim, ltrim,
-rtrim, strRepeat, paren} = @Js2coffeeHelpers or require('./helpers')
+{Code, p, strEscape, unreserve, unshift, isSingleLine, trim, blockTrim,
+ ltrim, rtrim, strRepeat, paren, truthy} = @Js2coffeeHelpers or require('./helpers')
# ## Main entry point
# This is `require('js2coffee').build()`. It takes a JavaScript source
@@ -462,13 +460,19 @@ class Builder
'while': (n) ->
c = new Code
- keyword = if n.positive then "while" else "until"
- body_ = @body(n.body)
+ keyword = if n.positive then "while" else "until"
+ body_ = @body(n.body)
- if isSingleLine(body_)
- c.add "#{trim body_} #{keyword} #{@build n.condition}\n"
+ # *Use `loop` whin something will go on forever (like `while (true)`).*
+ if truthy(n.condition)
+ statement = "loop"
else
- c.add "#{keyword} #{@build n.condition}"
+ statement = "#{keyword} #{@build n.condition}"
+
+ if isSingleLine(body_) and statement isnt "loop"
+ c.add "#{trim body_} #{statement}\n"
+ else
+ c.add statement
c.scope body_
c
View
@@ -0,0 +1,11 @@
+loop
+ continue
+loop
+ x()
+loop
+ continue
+loop
+ x()
+x() while 0.0
+loop
+ x()
View
@@ -0,0 +1,6 @@
+while (true) {}
+while (true) { x(); }
+while (100) {}
+while (100) { x(); }
+while (0.0) { x(); }
+while (0.01) { x(); }

0 comments on commit 591f364

Please sign in to comment.