diff --git a/String/CheckExceedingString.js b/String/CheckExceedingString.js new file mode 100644 index 0000000000..70df38b515 --- /dev/null +++ b/String/CheckExceedingString.js @@ -0,0 +1,33 @@ +// checks if a string is exceeding string or not +// Exceeding words are words where the gap between two adjacent characters is increasing. +// The gap is the distance in ascii +// More info at : https://github.com/TheAlgorithms/Javascript/issues/765 + +/** + * a function to check whether a string is exceedng or not + * @param str the str that should be checked + */ +function checkExceedingString(str) { + if (typeof str !== 'string') throw new TypeError('str must be a string!') + + const asciiArr = [] + + // collect the ascii of each letter + for (let s of str) asciiArr.push(s.charCodeAt()) + + let isExceeding = true + + for (let j = 0; j < asciiArr.length - 3; j++) { + // if the ascii of current letter is greater than the next letter it's not an exceeding string + let gapCond = + Math.abs(asciiArr[j] - asciiArr[j + 1]) > + Math.abs(asciiArr[j + 2] - asciiArr[j + 3]) + if (gapCond) { + isExceeding = false + break + } + } + return isExceeding +} + +module.exports = checkExceedingString diff --git a/String/test/CheckExceedingString.test.js b/String/test/CheckExceedingString.test.js new file mode 100644 index 0000000000..3c1ad57dd8 --- /dev/null +++ b/String/test/CheckExceedingString.test.js @@ -0,0 +1,19 @@ +const checkExceedingString = require('./CheckExceedingString') + +describe('check exceeding string', () => { + it('expect to throw an error if input is not a string', () => { + expect(() => checkExceedingString(null)).toThrow() + }) + + it('expects to return true if the input is exceeding string', () => { + const value = 'abcdef' + const result = checkExceedingString(value) + expect(result).toBe(true) + }) + + it('expects to return false if the input is not in camel case format', () => { + const value = 'happy' + const result = checkExceedingString(value) + expect(result).toBe(false) + }) +})