Fix/code smells (#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>
This commit is contained in:
Carlos Rafael
2023-08-21 15:06:43 -03:00
committed by GitHub
parent 9b32db29d8
commit 00e40e6f06
14 changed files with 33 additions and 111 deletions

View File

@ -23,8 +23,5 @@
*/
export const IsPowerOfTwo = (n) => {
if (n > 0 && (n & (n - 1)) === 0) {
return true
}
return false
return n > 0 && (n & (n - 1)) === 0
}

View File

@ -29,11 +29,12 @@ export function newGeneration (cells) {
// Decide whether the cell is alive or dead
const alive = cells[i][j] === 1
if ((alive && neighbourCount >= 2 && neighbourCount <= 3) || (!alive && neighbourCount === 3)) {
nextGenerationRow.push(1)
} else {
nextGenerationRow.push(0)
}
const cellIsAlive =
(alive && neighbourCount >= 2 && neighbourCount <= 3) ||
(!alive && neighbourCount === 3)
nextGenerationRow.push(cellIsAlive ? 1 : 0)
}
nextGeneration.push(nextGenerationRow)
}

View File

@ -19,7 +19,7 @@ const DateToDay = (dd, mm, yyyy) => {
const DateDayDifference = (date1, date2) => {
// firstly, check that both input are string or not.
if (typeof date1 !== 'string' && typeof date2 !== 'string') {
if (typeof date1 !== 'string' || typeof date2 !== 'string') {
return new TypeError('Argument is not a string.')
}
// extract the first date

View File

@ -1,5 +1,6 @@
* **Backtracking**
* [AllCombinationsOfSizeK](Backtracking/AllCombinationsOfSizeK.js)
* [generateParentheses](Backtracking/generateParentheses.js)
* [GeneratePermutations](Backtracking/GeneratePermutations.js)
* [KnightTour](Backtracking/KnightTour.js)
* [NQueens](Backtracking/NQueens.js)
@ -18,12 +19,14 @@
* [Memoize](Cache/Memoize.js)
* **Cellular-Automata**
* [ConwaysGameOfLife](Cellular-Automata/ConwaysGameOfLife.js)
* [Elementary](Cellular-Automata/Elementary.js)
* **Ciphers**
* [AffineCipher](Ciphers/AffineCipher.js)
* [Atbash](Ciphers/Atbash.js)
* [CaesarCipher](Ciphers/CaesarCipher.js)
* [KeyFinder](Ciphers/KeyFinder.js)
* [KeywordShiftedAlphabet](Ciphers/KeywordShiftedAlphabet.js)
* [MorseCode](Ciphers/MorseCode.js)
* [ROT13](Ciphers/ROT13.js)
* [VigenereCipher](Ciphers/VigenereCipher.js)
* [XORCipher](Ciphers/XORCipher.js)
@ -66,6 +69,7 @@
* [Graph2](Data-Structures/Graph/Graph2.js)
* [Graph3](Data-Structures/Graph/Graph3.js)
* **Heap**
* [KeyPriorityQueue](Data-Structures/Heap/KeyPriorityQueue.js)
* [MaxHeap](Data-Structures/Heap/MaxHeap.js)
* [MinHeap](Data-Structures/Heap/MinHeap.js)
* [MinPriorityQueue](Data-Structures/Heap/MinPriorityQueue.js)
@ -112,7 +116,10 @@
* [Shuf](Dynamic-Programming/Shuf.js)
* [SieveOfEratosthenes](Dynamic-Programming/SieveOfEratosthenes.js)
* **Sliding-Window**
* [HouseRobber](Dynamic-Programming/Sliding-Window/HouseRobber.js)
* [LongestSubstringWithoutRepeatingCharacters](Dynamic-Programming/Sliding-Window/LongestSubstringWithoutRepeatingCharacters.js)
* [MaxConsecutiveOnes](Dynamic-Programming/Sliding-Window/MaxConsecutiveOnes.js)
* [MaxConsecutiveOnesIII](Dynamic-Programming/Sliding-Window/MaxConsecutiveOnesIII.js)
* [PermutationinString](Dynamic-Programming/Sliding-Window/PermutationinString.js)
* [SudokuSolver](Dynamic-Programming/SudokuSolver.js)
* [TrappingRainWater](Dynamic-Programming/TrappingRainWater.js)
@ -212,6 +219,7 @@
* [ModularBinaryExponentiationRecursive](Maths/ModularBinaryExponentiationRecursive.js)
* [NumberOfDigits](Maths/NumberOfDigits.js)
* [Palindrome](Maths/Palindrome.js)
* [ParityOutlier](Maths/ParityOutlier.js)
* [PascalTriangle](Maths/PascalTriangle.js)
* [PerfectCube](Maths/PerfectCube.js)
* [PerfectNumber](Maths/PerfectNumber.js)
@ -365,7 +373,6 @@
* [Upper](String/Upper.js)
* [ValidateCreditCard](String/ValidateCreditCard.js)
* [ValidateEmail](String/ValidateEmail.js)
* [ValidateUrl](String/ValidateUrl.js)
* [ZFunction](String/ZFunction.js)
* **Timing-Functions**
* [GetMonthDays](Timing-Functions/GetMonthDays.js)

View File

@ -5,9 +5,7 @@ describe('Test Graph2', () => {
const graph = new Graph(vertices.length)
// adding vertices
for (let i = 0; i < vertices.length; i++) {
graph.addVertex(vertices[i])
}
vertices.forEach((vertice) => graph.addVertex(vertice))
// adding edges
graph.addEdge('A', 'B')
@ -27,7 +25,7 @@ describe('Test Graph2', () => {
expect(mockFn.mock.calls.length).toBe(vertices.length)
// Collect adjacency lists from output (call args)
const adjListArr = mockFn.mock.calls.map(v => v[0])
const adjListArr = mockFn.mock.calls.map((v) => v[0])
expect(adjListArr).toEqual([
'A -> B D E ',

View File

@ -47,8 +47,7 @@ class MinPriorityQueue {
// returns boolean value whether the heap is full or not
isFull () {
if (this.size === this.capacity) return true
return false
return this.size === this.capacity
}
// prints the heap

View File

@ -106,8 +106,8 @@ Trie.prototype.contains = function (word) {
// find the node with given prefix
const node = this.findPrefix(word)
// No such word exists
if (node === null || node.count === 0) return false
return true
return node !== null && node.count !== 0
}
Trie.prototype.findOccurrences = function (word) {

View File

@ -3,6 +3,7 @@
* And prints out the month's calendar.
* It uses an epoch of 1/1/1900, Monday.
*/
import { isLeapYear } from '../Maths/LeapYear'
class Month {
constructor () {
@ -51,11 +52,6 @@ class Month {
return dateOb
}
isLeapYear (year) {
if (((year % 400) === 0) || (((year % 100) !== 0) && ((year % 4) === 0))) return true
return false
}
isGreater (startDate, endDate) {
if (startDate.year > endDate.year) {
return true
@ -79,16 +75,16 @@ class Month {
}
let diff = 0
while (startDate.year !== endDate.year) {
diff += (this.isLeapYear(startDate.year)) ? 366 : 365
diff += (isLeapYear(startDate.year)) ? 366 : 365
startDate.year = startDate.year + 1
}
while (startDate.month !== endDate.month) {
if (startDate.month < endDate.month) {
if (this.isLeapYear(startDate.year)) diff += this.monthDaysLeap[startDate.month]
if (isLeapYear(startDate.year)) diff += this.monthDaysLeap[startDate.month]
else diff += this.monthDays[startDate.month]
startDate.month = startDate.month + 1
} else {
if (this.isLeapYear(startDate.year)) diff -= this.monthDaysLeap[startDate.month - 1]
if (isLeapYear(startDate.year)) diff -= this.monthDaysLeap[startDate.month - 1]
else diff -= this.monthDays[startDate.month - 1]
startDate.month = startDate.month - 1
}
@ -103,7 +99,7 @@ class Month {
let Month2 = this.parseDate(date)
day = (this.isGreater(Month2, this.epoch)) ? this.Days[difference] : this.BDays[difference]
Month2 = this.parseDate(date)
if (this.isLeapYear(Month2.year)) this.printCal(this.monthDaysLeap[Month2.month], day)
if (isLeapYear(Month2.year)) this.printCal(this.monthDaysLeap[Month2.month], day)
else this.printCal(this.monthDays[Month2.month], day)
}
}

View File

@ -41,70 +41,3 @@ function solve (graph, s) {
}
export { solve }
// // create graph
// const graph = {}
// const layout = {
// R: ['2'],
// 2: ['3', '4'],
// 3: ['4', '6', '13'],
// 4: ['5', '8'],
// 5: ['7', '11'],
// 6: ['13', '15'],
// 7: ['10'],
// 8: ['11', '13'],
// 9: ['14'],
// 10: [],
// 11: ['12'],
// 12: [],
// 13: ['14'],
// 14: [],
// 15: []
// }
// // convert uni-directional to bi-directional graph
// let graph = {
// a: {e:1, b:1, g:3},
// b: {a:1, c:1},
// c: {b:1, d:1},
// d: {c:1, e:1},
// e: {d:1, a:1},
// f: {g:1, h:1},
// g: {a:3, f:1},
// h: {f:1}
// };
// for (const id in layout) {
// if (!graph[id]) { graph[id] = {} }
// layout[id].forEach(function (aid) {
// graph[id][aid] = 1
// if (!graph[aid]) { graph[aid] = {} }
// graph[aid][id] = 1
// })
// }
// // choose start node
// const start = '10'
// // get all solutions
// const solutions = solve(graph, start)
// // for s in solutions..
// ' -> ' + s + ': [' + solutions[s].join(', ') + '] (dist:' + solutions[s].dist + ')'
// From '10' to
// -> 2: [7, 5, 4, 2] (dist:4)
// -> 3: [7, 5, 4, 3] (dist:4)
// -> 4: [7, 5, 4] (dist:3)
// -> 5: [7, 5] (dist:2)
// -> 6: [7, 5, 4, 3, 6] (dist:5)
// -> 7: [7] (dist:1)
// -> 8: [7, 5, 4, 8] (dist:4)
// -> 9: [7, 5, 4, 3, 13, 14, 9] (dist:7)
// -> 10: [] (dist:0)
// -> 11: [7, 5, 11] (dist:3)
// -> 12: [7, 5, 11, 12] (dist:4)
// -> 13: [7, 5, 4, 3, 13] (dist:5)
// -> 14: [7, 5, 4, 3, 13, 14] (dist:6)
// -> 15: [7, 5, 4, 3, 6, 15] (dist:6)
// -> R: [7, 5, 4, 2, R] (dist:5)

View File

@ -14,9 +14,5 @@
* @returns {boolean} true if this is a leap year, false otherwise.
*/
export const isLeapYear = (year) => {
if (year % 400 === 0) return true
if (year % 100 === 0) return false
if (year % 4 === 0) return true
return false
return ((year % 400) === 0) || (((year % 100) !== 0) && ((year % 4) === 0))
}

View File

@ -20,12 +20,9 @@ const matrixCheck = (matrix) => {
// 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.
const twoMatricesCheck = (first, second) => {
const [firstRowLength, secondRowLength, firstColLength, secondColLength] = [first.length, second.length, matrixCheck(first), matrixCheck(second)]
if (firstRowLength !== secondColLength || secondRowLength !== firstColLength) {
// These matrices do not have a common side
return false
} else {
return true
}
// These matrices do not have a common side
return firstRowLength === secondColLength && secondRowLength === firstColLength
}
// returns an empty array that has the same number of rows as the left matrix being multiplied.

View File

@ -41,8 +41,7 @@ function integralEvaluation (N, a, b, func) {
// Calculate the integral
let result = h
temp = 0
for (let i = 0; i < pointsArray.length; i++) temp += pointsArray[i]
temp = pointsArray.reduce((acc, currValue) => acc + currValue, 0)
result *= temp

View File

@ -54,8 +54,7 @@ function integralEvaluation (N, a, b, func) {
// Calculate the integral
let result = h / 3
temp = 0
for (let i = 0; i < pointsArray.length; i++) temp += pointsArray[i]
temp = pointsArray.reduce((acc, currValue) => acc + currValue, 0)
result *= temp

View File

@ -12,7 +12,7 @@ export const palindromeRearranging = (str) => {
return 'Not a string'
}
// Check if is a empty string
if (str.length === 0) {
if (!str) {
return 'Empty string'
}