Rewriting JavaScript in a shortcut in Ruby

I am porting the JavaScript library in Ruby and came across the following madness (greatly abbreviated):

function foo(){ if (foo) ... loop: while(go()){ if (...) break; switch(...){ case a: break loop; case b: case c: if (...) break loop; ... break; case d: if (...) break loop; // fall through case e: if (...) break loop; ... break; case f: if (...) break loop; object_init: do{ switch(...){ case a: ... break; case b: ... break object_init; } } while(...); ... break; } } } 

(You can view complete horror at lines 701-1006 .)

How would you rewrite this in Ruby? In particular:

  • Handling mixed break and break loop and
  • Handling random dips that occur in the switch

Presumably a good general strategy for them will lead me to other situations, such as a nested object_init gap.

Edit : how stupid I am; JavaScript fails as follows:

 switch(xxx){ case a: aaa; case b: bbb; break; } 

can be easily rewritten in Ruby as:

 case xxx when a, b if a===xxx aaa end bbb end 
+4
source share
1 answer

There are several methods that will work for this.

  • I am sure that this has already happened to you, but for the record you can extract methods from the nightmare function until its structure becomes more reasonable.

  • You can define outer contours with lambda , and then immediately call them on the next line. This will allow you to use the return statement as a layered break , and the closure created will allow you to access external scope variables.

  • You can create an exception and save it.

  • (Added by Phrogz) As suggested in the answer related to @jleedev, you can use throw / catch, for example.

     catch(:loop) do case ... when a throw :loop when b, c throw :loop if ... ... end end 
+4
source

Source: https://habr.com/ru/post/1339593/


All Articles