Skip to content

Commit 00e40e6

Browse files
CarlosZoftgithub-actions
and
github-actions
authored
Fix/code smells (TheAlgorithms#1338)
* ♻️ refactor: improving and fixing some code * Updated Documentation in README.md * ♻️ refactor: improving isLeapYear * 🐛 chore: back changes * 🐛 fix: using reduce instead forEach * 🐛 fix: using reduce instead forEach * 🐛 fix: removing duplicated code * 🐛 chore: removing .js --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com>
1 parent 9b32db2 commit 00e40e6

14 files changed

+33
-111
lines changed

Bit-Manipulation/IsPowerOfTwo.js

+1-4
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,5 @@
2323
*/
2424

2525
export const IsPowerOfTwo = (n) => {
26-
if (n > 0 && (n & (n - 1)) === 0) {
27-
return true
28-
}
29-
return false
26+
return n > 0 && (n & (n - 1)) === 0
3027
}

Cellular-Automata/ConwaysGameOfLife.js

+6-5
Original file line numberDiff line numberDiff line change
@@ -29,11 +29,12 @@ export function newGeneration (cells) {
2929

3030
// Decide whether the cell is alive or dead
3131
const alive = cells[i][j] === 1
32-
if ((alive && neighbourCount >= 2 && neighbourCount <= 3) || (!alive && neighbourCount === 3)) {
33-
nextGenerationRow.push(1)
34-
} else {
35-
nextGenerationRow.push(0)
36-
}
32+
33+
const cellIsAlive =
34+
(alive && neighbourCount >= 2 && neighbourCount <= 3) ||
35+
(!alive && neighbourCount === 3)
36+
37+
nextGenerationRow.push(cellIsAlive ? 1 : 0)
3738
}
3839
nextGeneration.push(nextGenerationRow)
3940
}

Conversions/DateDayDifference.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ const DateToDay = (dd, mm, yyyy) => {
1919

2020
const DateDayDifference = (date1, date2) => {
2121
// firstly, check that both input are string or not.
22-
if (typeof date1 !== 'string' && typeof date2 !== 'string') {
22+
if (typeof date1 !== 'string' || typeof date2 !== 'string') {
2323
return new TypeError('Argument is not a string.')
2424
}
2525
// extract the first date

DIRECTORY.md

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
* **Backtracking**
22
* [AllCombinationsOfSizeK](Backtracking/AllCombinationsOfSizeK.js)
3+
* [generateParentheses](Backtracking/generateParentheses.js)
34
* [GeneratePermutations](Backtracking/GeneratePermutations.js)
45
* [KnightTour](Backtracking/KnightTour.js)
56
* [NQueens](Backtracking/NQueens.js)
@@ -18,12 +19,14 @@
1819
* [Memoize](Cache/Memoize.js)
1920
* **Cellular-Automata**
2021
* [ConwaysGameOfLife](Cellular-Automata/ConwaysGameOfLife.js)
22+
* [Elementary](Cellular-Automata/Elementary.js)
2123
* **Ciphers**
2224
* [AffineCipher](Ciphers/AffineCipher.js)
2325
* [Atbash](Ciphers/Atbash.js)
2426
* [CaesarCipher](Ciphers/CaesarCipher.js)
2527
* [KeyFinder](Ciphers/KeyFinder.js)
2628
* [KeywordShiftedAlphabet](Ciphers/KeywordShiftedAlphabet.js)
29+
* [MorseCode](Ciphers/MorseCode.js)
2730
* [ROT13](Ciphers/ROT13.js)
2831
* [VigenereCipher](Ciphers/VigenereCipher.js)
2932
* [XORCipher](Ciphers/XORCipher.js)
@@ -66,6 +69,7 @@
6669
* [Graph2](Data-Structures/Graph/Graph2.js)
6770
* [Graph3](Data-Structures/Graph/Graph3.js)
6871
* **Heap**
72+
* [KeyPriorityQueue](Data-Structures/Heap/KeyPriorityQueue.js)
6973
* [MaxHeap](Data-Structures/Heap/MaxHeap.js)
7074
* [MinHeap](Data-Structures/Heap/MinHeap.js)
7175
* [MinPriorityQueue](Data-Structures/Heap/MinPriorityQueue.js)
@@ -112,7 +116,10 @@
112116
* [Shuf](Dynamic-Programming/Shuf.js)
113117
* [SieveOfEratosthenes](Dynamic-Programming/SieveOfEratosthenes.js)
114118
* **Sliding-Window**
119+
* [HouseRobber](Dynamic-Programming/Sliding-Window/HouseRobber.js)
115120
* [LongestSubstringWithoutRepeatingCharacters](Dynamic-Programming/Sliding-Window/LongestSubstringWithoutRepeatingCharacters.js)
121+
* [MaxConsecutiveOnes](Dynamic-Programming/Sliding-Window/MaxConsecutiveOnes.js)
122+
* [MaxConsecutiveOnesIII](Dynamic-Programming/Sliding-Window/MaxConsecutiveOnesIII.js)
116123
* [PermutationinString](Dynamic-Programming/Sliding-Window/PermutationinString.js)
117124
* [SudokuSolver](Dynamic-Programming/SudokuSolver.js)
118125
* [TrappingRainWater](Dynamic-Programming/TrappingRainWater.js)
@@ -212,6 +219,7 @@
212219
* [ModularBinaryExponentiationRecursive](Maths/ModularBinaryExponentiationRecursive.js)
213220
* [NumberOfDigits](Maths/NumberOfDigits.js)
214221
* [Palindrome](Maths/Palindrome.js)
222+
* [ParityOutlier](Maths/ParityOutlier.js)
215223
* [PascalTriangle](Maths/PascalTriangle.js)
216224
* [PerfectCube](Maths/PerfectCube.js)
217225
* [PerfectNumber](Maths/PerfectNumber.js)
@@ -365,7 +373,6 @@
365373
* [Upper](String/Upper.js)
366374
* [ValidateCreditCard](String/ValidateCreditCard.js)
367375
* [ValidateEmail](String/ValidateEmail.js)
368-
* [ValidateUrl](String/ValidateUrl.js)
369376
* [ZFunction](String/ZFunction.js)
370377
* **Timing-Functions**
371378
* [GetMonthDays](Timing-Functions/GetMonthDays.js)

Data-Structures/Graph/test/Graph2.test.js

+2-4
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,7 @@ describe('Test Graph2', () => {
55
const graph = new Graph(vertices.length)
66

77
// adding vertices
8-
for (let i = 0; i < vertices.length; i++) {
9-
graph.addVertex(vertices[i])
10-
}
8+
vertices.forEach((vertice) => graph.addVertex(vertice))
119

1210
// adding edges
1311
graph.addEdge('A', 'B')
@@ -27,7 +25,7 @@ describe('Test Graph2', () => {
2725
expect(mockFn.mock.calls.length).toBe(vertices.length)
2826

2927
// Collect adjacency lists from output (call args)
30-
const adjListArr = mockFn.mock.calls.map(v => v[0])
28+
const adjListArr = mockFn.mock.calls.map((v) => v[0])
3129

3230
expect(adjListArr).toEqual([
3331
'A -> B D E ',

Data-Structures/Heap/MinPriorityQueue.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,7 @@ class MinPriorityQueue {
4747

4848
// returns boolean value whether the heap is full or not
4949
isFull () {
50-
if (this.size === this.capacity) return true
51-
return false
50+
return this.size === this.capacity
5251
}
5352

5453
// prints the heap

Data-Structures/Tree/Trie.js

+2-2
Original file line numberDiff line numberDiff line change
@@ -106,8 +106,8 @@ Trie.prototype.contains = function (word) {
106106
// find the node with given prefix
107107
const node = this.findPrefix(word)
108108
// No such word exists
109-
if (node === null || node.count === 0) return false
110-
return true
109+
110+
return node !== null && node.count !== 0
111111
}
112112

113113
Trie.prototype.findOccurrences = function (word) {

Dynamic-Programming/FindMonthCalendar.js

+5-9
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
* And prints out the month's calendar.
44
* It uses an epoch of 1/1/1900, Monday.
55
*/
6+
import { isLeapYear } from '../Maths/LeapYear'
67

78
class Month {
89
constructor () {
@@ -51,11 +52,6 @@ class Month {
5152
return dateOb
5253
}
5354

54-
isLeapYear (year) {
55-
if (((year % 400) === 0) || (((year % 100) !== 0) && ((year % 4) === 0))) return true
56-
return false
57-
}
58-
5955
isGreater (startDate, endDate) {
6056
if (startDate.year > endDate.year) {
6157
return true
@@ -79,16 +75,16 @@ class Month {
7975
}
8076
let diff = 0
8177
while (startDate.year !== endDate.year) {
82-
diff += (this.isLeapYear(startDate.year)) ? 366 : 365
78+
diff += (isLeapYear(startDate.year)) ? 366 : 365
8379
startDate.year = startDate.year + 1
8480
}
8581
while (startDate.month !== endDate.month) {
8682
if (startDate.month < endDate.month) {
87-
if (this.isLeapYear(startDate.year)) diff += this.monthDaysLeap[startDate.month]
83+
if (isLeapYear(startDate.year)) diff += this.monthDaysLeap[startDate.month]
8884
else diff += this.monthDays[startDate.month]
8985
startDate.month = startDate.month + 1
9086
} else {
91-
if (this.isLeapYear(startDate.year)) diff -= this.monthDaysLeap[startDate.month - 1]
87+
if (isLeapYear(startDate.year)) diff -= this.monthDaysLeap[startDate.month - 1]
9288
else diff -= this.monthDays[startDate.month - 1]
9389
startDate.month = startDate.month - 1
9490
}
@@ -103,7 +99,7 @@ class Month {
10399
let Month2 = this.parseDate(date)
104100
day = (this.isGreater(Month2, this.epoch)) ? this.Days[difference] : this.BDays[difference]
105101
Month2 = this.parseDate(date)
106-
if (this.isLeapYear(Month2.year)) this.printCal(this.monthDaysLeap[Month2.month], day)
102+
if (isLeapYear(Month2.year)) this.printCal(this.monthDaysLeap[Month2.month], day)
107103
else this.printCal(this.monthDays[Month2.month], day)
108104
}
109105
}

Graphs/DijkstraSmallestPath.js

-67
Original file line numberDiff line numberDiff line change
@@ -41,70 +41,3 @@ function solve (graph, s) {
4141
}
4242

4343
export { solve }
44-
45-
// // create graph
46-
// const graph = {}
47-
48-
// const layout = {
49-
// R: ['2'],
50-
// 2: ['3', '4'],
51-
// 3: ['4', '6', '13'],
52-
// 4: ['5', '8'],
53-
// 5: ['7', '11'],
54-
// 6: ['13', '15'],
55-
// 7: ['10'],
56-
// 8: ['11', '13'],
57-
// 9: ['14'],
58-
// 10: [],
59-
// 11: ['12'],
60-
// 12: [],
61-
// 13: ['14'],
62-
// 14: [],
63-
// 15: []
64-
// }
65-
66-
// // convert uni-directional to bi-directional graph
67-
// let graph = {
68-
// a: {e:1, b:1, g:3},
69-
// b: {a:1, c:1},
70-
// c: {b:1, d:1},
71-
// d: {c:1, e:1},
72-
// e: {d:1, a:1},
73-
// f: {g:1, h:1},
74-
// g: {a:3, f:1},
75-
// h: {f:1}
76-
// };
77-
78-
// for (const id in layout) {
79-
// if (!graph[id]) { graph[id] = {} }
80-
// layout[id].forEach(function (aid) {
81-
// graph[id][aid] = 1
82-
// if (!graph[aid]) { graph[aid] = {} }
83-
// graph[aid][id] = 1
84-
// })
85-
// }
86-
87-
// // choose start node
88-
// const start = '10'
89-
// // get all solutions
90-
// const solutions = solve(graph, start)
91-
92-
// // for s in solutions..
93-
// ' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')'
94-
95-
// From '10' to
96-
// -> 2: [7, 5, 4, 2] (dist:4)
97-
// -> 3: [7, 5, 4, 3] (dist:4)
98-
// -> 4: [7, 5, 4] (dist:3)
99-
// -> 5: [7, 5] (dist:2)
100-
// -> 6: [7, 5, 4, 3, 6] (dist:5)
101-
// -> 7: [7] (dist:1)
102-
// -> 8: [7, 5, 4, 8] (dist:4)
103-
// -> 9: [7, 5, 4, 3, 13, 14, 9] (dist:7)
104-
// -> 10: [] (dist:0)
105-
// -> 11: [7, 5, 11] (dist:3)
106-
// -> 12: [7, 5, 11, 12] (dist:4)
107-
// -> 13: [7, 5, 4, 3, 13] (dist:5)
108-
// -> 14: [7, 5, 4, 3, 13, 14] (dist:6)
109-
// -> 15: [7, 5, 4, 3, 6, 15] (dist:6)
110-
// -> R: [7, 5, 4, 2, R] (dist:5)

Maths/LeapYear.js

+1-5
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,5 @@
1414
* @returns {boolean} true if this is a leap year, false otherwise.
1515
*/
1616
export const isLeapYear = (year) => {
17-
if (year % 400 === 0) return true
18-
if (year % 100 === 0) return false
19-
if (year % 4 === 0) return true
20-
21-
return false
17+
return ((year % 400) === 0) || (((year % 100) !== 0) && ((year % 4) === 0))
2218
}

Maths/MatrixMultiplication.js

+3-6
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,9 @@ const matrixCheck = (matrix) => {
2020
// tests to see if the matrices have a like side, i.e. the row length on the first matrix matches the column length on the second matrix, or vice versa.
2121
const twoMatricesCheck = (first, second) => {
2222
const [firstRowLength, secondRowLength, firstColLength, secondColLength] = [first.length, second.length, matrixCheck(first), matrixCheck(second)]
23-
if (firstRowLength !== secondColLength || secondRowLength !== firstColLength) {
24-
// These matrices do not have a common side
25-
return false
26-
} else {
27-
return true
28-
}
23+
24+
// These matrices do not have a common side
25+
return firstRowLength === secondColLength && secondRowLength === firstColLength
2926
}
3027

3128
// returns an empty array that has the same number of rows as the left matrix being multiplied.

Maths/MidpointIntegration.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,7 @@ function integralEvaluation (N, a, b, func) {
4141

4242
// Calculate the integral
4343
let result = h
44-
temp = 0
45-
for (let i = 0; i < pointsArray.length; i++) temp += pointsArray[i]
44+
temp = pointsArray.reduce((acc, currValue) => acc + currValue, 0)
4645

4746
result *= temp
4847

Maths/SimpsonIntegration.js

+1-2
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,7 @@ function integralEvaluation (N, a, b, func) {
5454

5555
// Calculate the integral
5656
let result = h / 3
57-
temp = 0
58-
for (let i = 0; i < pointsArray.length; i++) temp += pointsArray[i]
57+
temp = pointsArray.reduce((acc, currValue) => acc + currValue, 0)
5958

6059
result *= temp
6160

String/CheckRearrangePalindrome.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ export const palindromeRearranging = (str) => {
1212
return 'Not a string'
1313
}
1414
// Check if is a empty string
15-
if (str.length === 0) {
15+
if (!str) {
1616
return 'Empty string'
1717
}
1818

0 commit comments

Comments
 (0)