Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A simple example #263

Open
jonasseglare opened this issue Mar 25, 2015 · 0 comments
Open

A simple example #263

jonasseglare opened this issue Mar 25, 2015 · 0 comments

Comments

@jonasseglare
Copy link

Hi,

I just want to contribute with a simple example in case you are interested:

// Compile this file with
//
// _node -c hello._js
//
// or run it directly with
//
// _node hello._js

// Recursive implementation
function factorial(n, _) {
    if (n < 0) {

    // Is this the proper way to produce an error?
    throw new Error('An error');

    } else {
    if (n == 0) {
        return 1; // <-- will result int callback being called.
    } else {
        var subresult = factorial(n-1, _);
        return n*subresult; // <-- will result in callback being called.
    }
    }
}

// Delivers the result by calling a callback.
function multiply(a, b, _) {

    // This return statement will produce a callback.
    return a*b;
}

// Iterative implementation
function factorial2(n, _) {
    var result = 1;

    // Iterations with callbacks also work :-)
    for (var i = 1; i <= n; i++) {

    // Call to callback-style multiply.
    result = multiply(result, i, _);
    }

    // Will call the callback.
    return result;
}

// Non-callback-based factorial
function factorial3(n) {
    if (n == 0) {
    return 1;
    } else {
    return n*factorial3(n - 1);
    }
}

var x = 9;
var y = factorial(x, _);
var y2 = factorial2(x, _);
var y3 = factorial3(x);

// Please note that all y's will be evaluated before we reach this point :-)
console.log('Factorial of ' + x + ' is ' + y + ' or ' + y2 + ' or ' + y3);




///////////////////////////////////// INVESTIGATE STRATEGIES FOR ERROR HANDLING
var errorHandling = 'traditional'

if (errorHandling == 'none') { 
    console.log('Calling factorial with a negative number, NO ERROR HANDLING: ', factorial(-30, _));
} else if (errorHandling == 'traditional') {
    factorial(
        -30,
    function(err, value) {
        console.log('Calling factorial with a negative number, WITH ERROR HANDLING: ');
        console.log('err = ', err);
        console.log('value = ', value);
    }
    );
} else {
    try {
    console.log('Calling factorial with a negative number, IN TRY STATEMENT: ', factorial(-30, _));
    } catch (e) {
    console.log('Exception caught trying to evaluate factorial with negative number');
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants