From ee584c2f5a772318a5b2e906e619596eec9dd527 Mon Sep 17 00:00:00 2001 From: NadaJrad Date: Fri, 15 Mar 2024 11:53:19 +0100 Subject: [PATCH] nodejs week1 --- 6_nodejs/week1/avg.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 6_nodejs/week1/avg.js diff --git a/6_nodejs/week1/avg.js b/6_nodejs/week1/avg.js new file mode 100644 index 00000000..0669f139 --- /dev/null +++ b/6_nodejs/week1/avg.js @@ -0,0 +1,28 @@ +// avg.js + +// Get the command line arguments excluding the first two (which are node and the script name) +const args = process.argv.slice(2); + +if (args.length === 0) { + console.log("You need to enter some numbers"); +} else { + // Check if all arguments are valid numbers + const numbers = args.map(Number); + const filteredNumbers = numbers.filter(num => !isNaN(num)); + + if (filteredNumbers.length !== numbers.length) { + console.log("Some arguments are not numbers. Please provide valid numbers."); + } else { + const average = calculateAverage(numbers); + console.log(average); + } +} + +// Function to calculate the average of numbers +function calculateAverage(numbersArray) { + let sum = 0; + for (let i = 0; i < numbersArray.length; i++) { + sum += numbersArray[i]; + } + return sum / numbersArray.length; +} \ No newline at end of file