diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..002f89c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +node_modules/ diff --git a/package-lock.json b/package-lock.json index 8fce75c..8e2718d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7,7 +7,7 @@ "": { "name": "nodejs-practice-repository", "version": "1.0.0", - "license": "ISC", + "license": "MIT", "devDependencies": { "jest": "^29.7.0" } diff --git a/src/utils/gcd.js b/src/utils/gcd.js new file mode 100644 index 0000000..5c36463 --- /dev/null +++ b/src/utils/gcd.js @@ -0,0 +1,28 @@ +/** + * Author: Aisha Keller + * Date: 2 June 2026 + * File: gcd.js + * Description: This script calculates the greatest common divisor of two numbers + */ + +'use strict'; + +// The gcd function calculates the greates common divisor of two numbers +function gcd(a, b) { + +// If either number is negative, throw an error +if (a < 0 || b < 0) { + throw new Error('GCD of negative numbers is not defined'); +} + +// Use the Euclidean alorithm to calculate the GCD +while (b !== 0) { + let temp = b; + b = a % b; + a = temp; +} + +return a; // Return the GCD +} + +module.exports = { gcd }; // Export the gcd function for use in other scripts \ No newline at end of file diff --git a/test/utils/gcd.spec.js b/test/utils/gcd.spec.js new file mode 100644 index 0000000..4303e67 --- /dev/null +++ b/test/utils/gcd.spec.js @@ -0,0 +1,32 @@ +/** + * Author: Aisha Keller + * Date: 2 June 2026 + * File: gcd.spec.js + * Description: This script tests the gcd function. + */ + +'use strict'; + +const { gcd } = require('../../src/utils/gcd'); // Import the gcd function from the gcd.js file + +// The describe() function is a test suite that contains one or more tests +describe('gcd.js', () => { + +// Test 1: The it() should calculate the GCD of 12 and 8 +it('should calculate the GCD of 12 and 8', () => { + const result = gcd(12, 8); // Call the gcd function with the values of 12 and 8; + expect(result).toBe(4); // The expected result is 4 +}); + +// Test 2: The it() should calculate the GCD of 100 and 25 +it('should calculate the GCD of 100 and 25', () => { + const result = gcd(100, 25); // Call the gcd function with the values of 100 and 25 + expect(result).toBe(25); // The expected result is 25 +}); + +// Test 3: The it() should throw an error when calculating the GCD of a negative number +it('should throw an error when calculating the GCD of a negative number', () => { + // Call the gcd function with the values of -12 and 8 and expect it to throw an error + expect(() => gcd(-1, 5)).toThrow('GCD of negative numbers is not defined'); +}); +}); \ No newline at end of file