Skip to content

Commit 041918d

Browse files
authored
merge: Upgrade Lower function (TheAlgorithms#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
1 parent 29a3ab7 commit 041918d

File tree

2 files changed

+21
-16
lines changed

2 files changed

+21
-16
lines changed

String/Lower.js

+7-12
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/**
22
* @function lower
33
* @description Will convert the entire string to lowercase letters.
4-
* @param {String} url - The input URL string
5-
* @return {String} Lowercase string
4+
* @param {String} str - The input string
5+
* @returns {String} Lowercase string
66
* @example lower("HELLO") => hello
77
* @example lower("He_llo") => he_llo
88
*/
@@ -12,17 +12,12 @@ const lower = (str) => {
1212
throw new TypeError('Invalid Input Type')
1313
}
1414

15-
let lowerString = ''
15+
return str
16+
.replace(/[A-Z]/g, (_, indexOfUpperChar) => {
17+
const asciiCode = str.charCodeAt(indexOfUpperChar)
1618

17-
for (const char of str) {
18-
let asciiCode = char.charCodeAt(0)
19-
if (asciiCode >= 65 && asciiCode <= 90) {
20-
asciiCode += 32
21-
}
22-
lowerString += String.fromCharCode(asciiCode)
23-
}
24-
25-
return lowerString
19+
return String.fromCharCode(asciiCode + 32)
20+
})
2621
}
2722

2823
export { lower }

String/test/Lower.test.js

+14-4
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
11
import { lower } from '../Lower'
22

3-
describe('Lower', () => {
4-
it('return uppercase strings', () => {
5-
expect(lower('hello')).toBe('hello')
3+
describe('Testing the Lower function', () => {
4+
it('Test 1: Check by invalid type', () => {
5+
expect(() => lower(345)).toThrowError()
6+
expect(() => lower(true)).toThrowError()
7+
expect(() => lower(null)).toThrowError()
8+
})
9+
10+
it('Test 2: Check by uppercase string', () => {
611
expect(lower('WORLD')).toBe('world')
7-
expect(lower('hello_WORLD')).toBe('hello_world')
12+
expect(lower('Hello_WORLD')).toBe('hello_world')
13+
})
14+
15+
it('Test 3: Check by lowercase string', () => {
16+
expect(lower('hello')).toBe('hello')
17+
expect(lower('hello_world')).toBe('hello_world')
818
})
919
})

0 commit comments

Comments
 (0)