Skip to content

Commit 11ab8e1

Browse files
committed
String reversal
1 parent 180a11b commit 11ab8e1

File tree

4 files changed

+76
-1
lines changed

4 files changed

+76
-1
lines changed

README.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,6 @@ A collection of some JS algorithms
55
To run the tests for each algorithm, open up your terminal and navigate to the root directory of the codebase.
66
Once inside, run the command below:
77

8-
```npm run test <folder name>```
8+
```npm run test <folder name>```
9+
10+
1. String reversal

src/stringReversal/index.js

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
// pick a solution and insert here to run the test.
2+
3+
4+
function reverseString(text) {
5+
return text.split("").reduce((acc, char) => char + acc);
6+
}
7+
8+
module.exports = reverseString

src/stringReversal/solutions.js

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
// CHAINING BUILT-IN METHODS
2+
3+
function reverseString(text) {
4+
return text.split("").reverse().join("");
5+
}
6+
7+
// CHAINING BUILT-IN METHODS USING ES6
8+
9+
function reverseString(text) {
10+
return [...text].reverse().join('');
11+
}
12+
13+
// USING A FOR LOOP
14+
15+
function reverseString(text) {
16+
let result = "";
17+
for (let i = text.length - 1; i >= 0; i--) {
18+
result += text[i];
19+
}
20+
return result;
21+
}
22+
23+
// USING A FOR..OF LOOP IN ES6
24+
25+
function reverseString(text) {
26+
let result = "";
27+
for (let char of text) {
28+
result = char + result
29+
}
30+
return result;
31+
}
32+
33+
// RECURSIVE METHOD
34+
35+
function reverseString(text) {
36+
if (text === "") {
37+
return ""
38+
} else {
39+
return reverseString(text.substr(1)) + text[0]
40+
}
41+
}
42+
43+
44+
// USING .REDUCE()
45+
46+
function reverseString(text) {
47+
return text.split("").reduce((acc, char) => char + acc);
48+
}

src/stringReversal/test.js

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
const reverseString = require('./index')
2+
3+
test('reverseString is a function', () => {
4+
expect(typeof reverseString).toEqual('function');
5+
});
6+
7+
test('reverses a string of text', () => {
8+
expect(reverseString('aeiou')).toEqual('uoiea');
9+
});
10+
11+
test('reverses a string containing numbers', () => {
12+
expect(reverseString('123456789')).toEqual('987654321');
13+
});
14+
15+
test('reverses a string containing mixed case characters', () => {
16+
expect(reverseString('AsDfGhJkL')).toEqual('LkJhGfDsA');
17+
});

0 commit comments

Comments
 (0)