mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
merge: Upgrade Lower function (#894)
* docs: update the js doc * pref: Optimize algo via regex ignore the useless traverse in best case via regex and String.prototype.replace * test: add some new test cases * fix: styled with standard * refactor: remove useless variable
This commit is contained in:
@ -1,8 +1,8 @@
|
|||||||
/**
|
/**
|
||||||
* @function lower
|
* @function lower
|
||||||
* @description Will convert the entire string to lowercase letters.
|
* @description Will convert the entire string to lowercase letters.
|
||||||
* @param {String} url - The input URL string
|
* @param {String} str - The input string
|
||||||
* @return {String} Lowercase string
|
* @returns {String} Lowercase string
|
||||||
* @example lower("HELLO") => hello
|
* @example lower("HELLO") => hello
|
||||||
* @example lower("He_llo") => he_llo
|
* @example lower("He_llo") => he_llo
|
||||||
*/
|
*/
|
||||||
@ -12,17 +12,12 @@ const lower = (str) => {
|
|||||||
throw new TypeError('Invalid Input Type')
|
throw new TypeError('Invalid Input Type')
|
||||||
}
|
}
|
||||||
|
|
||||||
let lowerString = ''
|
return str
|
||||||
|
.replace(/[A-Z]/g, (_, indexOfUpperChar) => {
|
||||||
|
const asciiCode = str.charCodeAt(indexOfUpperChar)
|
||||||
|
|
||||||
for (const char of str) {
|
return String.fromCharCode(asciiCode + 32)
|
||||||
let asciiCode = char.charCodeAt(0)
|
})
|
||||||
if (asciiCode >= 65 && asciiCode <= 90) {
|
|
||||||
asciiCode += 32
|
|
||||||
}
|
|
||||||
lowerString += String.fromCharCode(asciiCode)
|
|
||||||
}
|
|
||||||
|
|
||||||
return lowerString
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export { lower }
|
export { lower }
|
||||||
|
@ -1,9 +1,19 @@
|
|||||||
import { lower } from '../Lower'
|
import { lower } from '../Lower'
|
||||||
|
|
||||||
describe('Lower', () => {
|
describe('Testing the Lower function', () => {
|
||||||
it('return uppercase strings', () => {
|
it('Test 1: Check by invalid type', () => {
|
||||||
expect(lower('hello')).toBe('hello')
|
expect(() => lower(345)).toThrowError()
|
||||||
|
expect(() => lower(true)).toThrowError()
|
||||||
|
expect(() => lower(null)).toThrowError()
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Test 2: Check by uppercase string', () => {
|
||||||
expect(lower('WORLD')).toBe('world')
|
expect(lower('WORLD')).toBe('world')
|
||||||
expect(lower('hello_WORLD')).toBe('hello_world')
|
expect(lower('Hello_WORLD')).toBe('hello_world')
|
||||||
|
})
|
||||||
|
|
||||||
|
it('Test 3: Check by lowercase string', () => {
|
||||||
|
expect(lower('hello')).toBe('hello')
|
||||||
|
expect(lower('hello_world')).toBe('hello_world')
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
Reference in New Issue
Block a user