NodeJS Slip 2A solution

Step 1:

Create a file named factorial.js for the user-defined module:
// Function to calculate factorial
function calculateFactorial(number) {
if (number === 0 || number === 1) {
return 1;
} else {
return number * calculateFactorial(number - 1);
}
}
// Export the function to make it accessible from other files
module.exports = calculateFactorial;

Step 2:

Create the main application file, for example, app.js:

// Import the user-defined module
const calculateFactorial = require('./factorial');
// Get user input (number for which factorial needs to be calculated)
const userInput = process.argv[2];
// Check if user provided a number
if (!userInput || isNaN(userInput)) {
console.log('Please provide a valid number as a command-line argument.');
process.exit(1); // Exit the process with an error code
}
// Parse the user input as an integer
const number = parseInt(userInput);
// Calculate the factorial using the user-defined module
const result = calculateFactorial(number);
// Display the result
console.log('The factorial of ${number} is: ${result}');

No comments:

Post a Comment