You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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');
}
}
The text was updated successfully, but these errors were encountered:
Hi,
I just want to contribute with a simple example in case you are interested:
The text was updated successfully, but these errors were encountered: