Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/klntsky/reto-js

Return from outer functions
https://github.com/klntsky/reto-js

Last synced: 19 days ago
JSON representation

Return from outer functions

Awesome Lists containing this project

README

        

Usage


(() => {

(() => {
(() => {
// Imagine you need to return a value as a result of
// the outermost function right from here
})();
// and make sure that this
})();
// and this areas of code will not be reached.
})();

off course there is a solution: use one more variable


(() => {

var tmp;
(() => {
(() => {
tmp = "foo";
return;
})();

if (typeof tmp != 'undefined') {
return;
}

// unreachable if `tmp` is set
})();

if (typeof tmp != 'undefined') {
return;
}

// unreachable if `tmp` is set
})();


but the code seems a little messy now.


reto.js allows to do it in a more elegant manner:


$label('example', () => {

(() => {
(() => {
$return('example', 'some_value');
})();
})();
});

How it works


$return throws an object containing the return value, that is later catched by a function made by $label.


That means, you can't use try .. catch .. finally blocks normally in any code that utilizes reto.js. Since exceptions used to pass values to outer labeled functions mustn't be catched by your code, you need to use $rethrow function provided by the library in the very beginning of every catch block where unwanted exception can appear. $rethrow just rethrows given exception if it was generated by $return and does nothing otherwise.


Example usage:


var r = $label('foo', () => {

try {
$return('foo', 'some-value');
} catch (e) {
$rethrow(e);
return 'another-value';
}
});

The above example outputs 'some-value as expected.


Functions


$label


Used to mark given function with label. Order of the arguments is completely ignored. string argument defines label value and bool argument determines if the wrapped function will be returned (true) or will it be called immedeately (false, default behavior).


$return


If called with two arguments, the first argument may be:



  • a label, to which the value need to be returned.

  • a natural number, defining how many nested levels of labeled functions you need to return from.


If called with one argument, value will be returned one level up.


$rethrow


Rethrows given exception if it was generated by $return and does nothing otherwise.