mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-08 12:35:16 +08:00
feat: Test running overhaul, switch to Prettier & reformat everything (#1407)
* chore: Switch to Node 20 + Vitest * chore: migrate to vitest mock functions * chore: code style (switch to prettier) * test: re-enable long-running test Seems the switch to Node 20 and Vitest has vastly improved the code's and / or the test's runtime! see #1193 * chore: code style * chore: fix failing tests * Updated Documentation in README.md * Update contribution guidelines to state usage of Prettier * fix: set prettier printWidth back to 80 * chore: apply updated code style automatically * fix: set prettier line endings to lf again * chore: apply updated code style automatically --------- Co-authored-by: github-actions <${GITHUB_ACTOR}@users.noreply.github.com> Co-authored-by: Lars Müller <34514239+appgurueu@users.noreply.github.com>
This commit is contained in:
@ -20,11 +20,12 @@ const alphaNumericPalindrome = (str) => {
|
||||
}
|
||||
|
||||
// removing all the special characters and turning everything to lowercase
|
||||
const newStr = str.replace(/[^a-z0-9]+/ig, '').toLowerCase()
|
||||
const newStr = str.replace(/[^a-z0-9]+/gi, '').toLowerCase()
|
||||
const midIndex = newStr.length >> 1 // x >> y = floor(x / 2^y)
|
||||
|
||||
for (let i = 0; i < midIndex; i++) {
|
||||
if (newStr.at(i) !== newStr.at(~i)) { // ~n = -(n + 1)
|
||||
if (newStr.at(i) !== newStr.at(~i)) {
|
||||
// ~n = -(n + 1)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
@ -22,7 +22,10 @@ const AlternativeStringArrange = (str1, str2) => {
|
||||
// get second string length.
|
||||
const secondStringLength = str2.length
|
||||
// absolute length for operation.
|
||||
const absLength = firstStringLength > secondStringLength ? firstStringLength : secondStringLength
|
||||
const absLength =
|
||||
firstStringLength > secondStringLength
|
||||
? firstStringLength
|
||||
: secondStringLength
|
||||
|
||||
// Iterate the character count until the absolute count is reached.
|
||||
for (let charCount = 0; charCount < absLength; charCount++) {
|
||||
|
@ -11,9 +11,7 @@ const checkExceeding = (str) => {
|
||||
throw new TypeError('Argument is not a string')
|
||||
}
|
||||
|
||||
const upperChars = str
|
||||
.toUpperCase()
|
||||
.replace(/[^A-Z]/g, '') // remove all from str except A to Z alphabets
|
||||
const upperChars = str.toUpperCase().replace(/[^A-Z]/g, '') // remove all from str except A to Z alphabets
|
||||
|
||||
const adjacentDiffList = []
|
||||
|
||||
|
@ -24,7 +24,7 @@ const checkPangramRegex = (string) => {
|
||||
* Dot - . -> Matches any character except linebreaks. Equivalent to
|
||||
* Star - * -> Matches 0 or more of the preceding token.
|
||||
* Numeric reference - \{$n} -> Matches the results of a capture group. E.g. - \1 matches the results of the first capture group & \3 matches the third.
|
||||
*/
|
||||
*/
|
||||
return string.match(/([a-z])(?!.*\1)/gi).length === 26
|
||||
}
|
||||
|
||||
|
@ -1,10 +1,10 @@
|
||||
/**
|
||||
* What is a palindrome? https://en.wikipedia.org/wiki/Palindrome
|
||||
* Receives a string and returns whether it can be rearranged to become a palindrome or not
|
||||
* The string can only be a palindrome if the count of ALL characters is even or if the ONLY ONE character count is odd
|
||||
* Input is a string
|
||||
*
|
||||
**/
|
||||
* What is a palindrome? https://en.wikipedia.org/wiki/Palindrome
|
||||
* Receives a string and returns whether it can be rearranged to become a palindrome or not
|
||||
* The string can only be a palindrome if the count of ALL characters is even or if the ONLY ONE character count is odd
|
||||
* Input is a string
|
||||
*
|
||||
**/
|
||||
|
||||
export const palindromeRearranging = (str) => {
|
||||
// check that input is a string
|
||||
@ -23,7 +23,9 @@ export const palindromeRearranging = (str) => {
|
||||
return counts
|
||||
}, {})
|
||||
// If the length of the resulting array is 0 or 1, the string can be a palindrome.
|
||||
return Object.values(charCounts).filter(count => count % 2 !== 0).length <= 1
|
||||
return (
|
||||
Object.values(charCounts).filter((count) => count % 2 !== 0).length <= 1
|
||||
)
|
||||
}
|
||||
|
||||
// testing
|
||||
|
@ -18,13 +18,10 @@ const checkWordOccurrence = (str, isCaseSensitive = false) => {
|
||||
|
||||
return modifiedStr
|
||||
.split(/\s+/) // remove all spaces and distribute all word in List
|
||||
.reduce(
|
||||
(occurrence, word) => {
|
||||
occurrence[word] = occurrence[word] + 1 || 1
|
||||
return occurrence
|
||||
},
|
||||
{}
|
||||
)
|
||||
.reduce((occurrence, word) => {
|
||||
occurrence[word] = occurrence[word] + 1 || 1
|
||||
return occurrence
|
||||
}, {})
|
||||
}
|
||||
|
||||
export { checkWordOccurrence }
|
||||
|
@ -5,7 +5,7 @@ More at : https://en.wikipedia.org/wiki/Permutation
|
||||
*/
|
||||
|
||||
const createPermutations = (str) => {
|
||||
// convert string to array
|
||||
// convert string to array
|
||||
const arr = str.split('')
|
||||
|
||||
// get array length
|
||||
@ -18,7 +18,9 @@ const createPermutations = (str) => {
|
||||
let next
|
||||
|
||||
// if strLen is zero, return the same string
|
||||
if (strLen === 0) { return [str] }
|
||||
if (strLen === 0) {
|
||||
return [str]
|
||||
}
|
||||
// loop to the length to get all permutations
|
||||
for (let i = 0; i < strLen; i++) {
|
||||
rest = Object.create(arr)
|
||||
|
@ -8,7 +8,7 @@
|
||||
// Time complexity: O(m + n), m and n being the sizes of string A and string B
|
||||
|
||||
// Find the bistrings of a string and return a hashmap (key => bistring, value => count)
|
||||
function mapBigrams (string) {
|
||||
function mapBigrams(string) {
|
||||
const bigrams = new Map()
|
||||
for (let i = 0; i < string.length - 1; i++) {
|
||||
const bigram = string.substring(i, i + 2)
|
||||
@ -20,7 +20,7 @@ function mapBigrams (string) {
|
||||
|
||||
// Calculate the number of common bigrams between a map of bigrams and a string
|
||||
|
||||
function countCommonBigrams (bigrams, string) {
|
||||
function countCommonBigrams(bigrams, string) {
|
||||
let count = 0
|
||||
for (let i = 0; i < string.length - 1; i++) {
|
||||
const bigram = string.substring(i, i + 2)
|
||||
@ -30,7 +30,7 @@ function countCommonBigrams (bigrams, string) {
|
||||
}
|
||||
|
||||
// Calculate Dice coeff of 2 strings
|
||||
function diceCoefficient (stringA, stringB) {
|
||||
function diceCoefficient(stringA, stringB) {
|
||||
if (stringA === stringB) return 1
|
||||
else if (stringA.length < 2 || stringB.length < 2) return 0
|
||||
|
||||
|
@ -4,7 +4,7 @@
|
||||
* @returns {string} - Format to (XXX) XXX-XXXX pattern
|
||||
*/
|
||||
const formatPhoneNumber = (phoneNumber) => {
|
||||
if ((phoneNumber.length !== 10) || isNaN(phoneNumber)) {
|
||||
if (phoneNumber.length !== 10 || isNaN(phoneNumber)) {
|
||||
// return "Invalid phone number."
|
||||
throw new TypeError('Invalid phone number!')
|
||||
}
|
||||
|
@ -7,10 +7,12 @@ The function generate an RFC4122 (https://www.ietf.org/rfc/rfc4122.txt) version
|
||||
export const Guid = () => {
|
||||
const pattern = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
|
||||
let currentDateMilliseconds = new Date().getTime()
|
||||
return pattern.replace(/[xy]/g, currentChar => {
|
||||
return pattern.replace(/[xy]/g, (currentChar) => {
|
||||
const randomChar = (currentDateMilliseconds + Math.random() * 16) % 16 | 0
|
||||
currentDateMilliseconds = Math.floor(currentDateMilliseconds / 16)
|
||||
return (currentChar === 'x' ? randomChar : (randomChar & 0x7 | 0x8)).toString(16)
|
||||
return (
|
||||
currentChar === 'x' ? randomChar : (randomChar & 0x7) | 0x8
|
||||
).toString(16)
|
||||
})
|
||||
}
|
||||
|
||||
|
@ -16,7 +16,7 @@
|
||||
- O(1)
|
||||
*/
|
||||
|
||||
export function isPalindromeIterative (x) {
|
||||
export function isPalindromeIterative(x) {
|
||||
if (typeof x !== 'string' && typeof x !== 'number') {
|
||||
throw new TypeError('Input must be a string or a number')
|
||||
}
|
||||
|
@ -12,8 +12,8 @@ const lower = (str) => {
|
||||
throw new TypeError('Invalid Input Type')
|
||||
}
|
||||
|
||||
return str.replace(
|
||||
/[A-Z]/g, (char) => String.fromCharCode(char.charCodeAt() + 32)
|
||||
return str.replace(/[A-Z]/g, (char) =>
|
||||
String.fromCharCode(char.charCodeAt() + 32)
|
||||
)
|
||||
}
|
||||
|
||||
|
@ -5,7 +5,8 @@
|
||||
* @param {RegExp} ignorePattern - ignore the char in str that is not required
|
||||
* @returns {string} - char
|
||||
*/
|
||||
const maxCharacter = (str, ignorePattern) => { // initially it's count only alphabets
|
||||
const maxCharacter = (str, ignorePattern) => {
|
||||
// initially it's count only alphabets
|
||||
if (typeof str !== 'string') {
|
||||
throw new TypeError('Argument should be a string')
|
||||
} else if (!str) {
|
||||
|
@ -22,13 +22,21 @@ const maxWord = (sentence = '') => {
|
||||
}
|
||||
|
||||
const occurrences = {}
|
||||
words.forEach(word => {
|
||||
occurrences[word.toLocaleLowerCase()] = occurrences[word.toLocaleLowerCase()] + 1 || 1
|
||||
words.forEach((word) => {
|
||||
occurrences[word.toLocaleLowerCase()] =
|
||||
occurrences[word.toLocaleLowerCase()] + 1 || 1
|
||||
})
|
||||
|
||||
const max = Object.keys(occurrences).reduce((n, word) => {
|
||||
if (occurrences[word] > n.count) { return { word, count: occurrences[word] } } else { return n }
|
||||
}, { word: '', count: 0 })
|
||||
const max = Object.keys(occurrences).reduce(
|
||||
(n, word) => {
|
||||
if (occurrences[word] > n.count) {
|
||||
return { word, count: occurrences[word] }
|
||||
} else {
|
||||
return n
|
||||
}
|
||||
},
|
||||
{ word: '', count: 0 }
|
||||
)
|
||||
|
||||
return max.word
|
||||
}
|
||||
|
@ -8,17 +8,23 @@ const permutate = (aString) => {
|
||||
let permutations = [[characters.shift()]]
|
||||
while (characters.length) {
|
||||
const currentCharacter = characters.shift()
|
||||
permutations = calculateCurrentCharacterPermutation(permutations, currentCharacter)
|
||||
permutations = calculateCurrentCharacterPermutation(
|
||||
permutations,
|
||||
currentCharacter
|
||||
)
|
||||
}
|
||||
return permutations
|
||||
.map(character => character.join(''))
|
||||
.filter((item, index, self) => (self.indexOf(item) === index))
|
||||
.map((character) => character.join(''))
|
||||
.filter((item, index, self) => self.indexOf(item) === index)
|
||||
.sort()
|
||||
}
|
||||
|
||||
const calculateCurrentCharacterPermutation = (allPermutations, currentCharacter) => {
|
||||
const calculateCurrentCharacterPermutation = (
|
||||
allPermutations,
|
||||
currentCharacter
|
||||
) => {
|
||||
const currentPermutations = []
|
||||
allPermutations.forEach(permutation => {
|
||||
allPermutations.forEach((permutation) => {
|
||||
let index = 0
|
||||
while (index <= permutation.length) {
|
||||
const tmp = [...permutation]
|
||||
|
@ -1,7 +1,7 @@
|
||||
/**
|
||||
* A short example showing how to reverse a string.
|
||||
*/
|
||||
function ReverseStringIterative (string) {
|
||||
function ReverseStringIterative(string) {
|
||||
if (typeof string !== 'string') {
|
||||
throw new TypeError('The given value is not a string')
|
||||
}
|
||||
@ -17,14 +17,14 @@ function ReverseStringIterative (string) {
|
||||
|
||||
/**
|
||||
*
|
||||
* @author dev-madhurendra
|
||||
* Reverses a number by converting it to a string.
|
||||
*
|
||||
* @param {string} str - The number to reverse.
|
||||
* @returns {string} The reversed number.
|
||||
*
|
||||
* @example
|
||||
* const reversed = reverseString("hello"); // Returns olleh
|
||||
* @author dev-madhurendra
|
||||
* Reverses a number by converting it to a string.
|
||||
*
|
||||
* @param {string} str - The number to reverse.
|
||||
* @returns {string} The reversed number.
|
||||
*
|
||||
* @example
|
||||
* const reversed = reverseString("hello"); // Returns olleh
|
||||
*/
|
||||
|
||||
const ReverseStringIterativeInplace = (str) => [...str].reverse().join('')
|
||||
|
@ -11,8 +11,8 @@ const upper = (str) => {
|
||||
throw new TypeError('Argument should be string')
|
||||
}
|
||||
|
||||
return str.replace(
|
||||
/[a-z]/g, (char) => String.fromCharCode(char.charCodeAt() - 32)
|
||||
return str.replace(/[a-z]/g, (char) =>
|
||||
String.fromCharCode(char.charCodeAt() - 32)
|
||||
)
|
||||
}
|
||||
|
||||
|
@ -43,10 +43,14 @@ const validateCreditCard = (creditCardString) => {
|
||||
throw new TypeError(errorMessage + 'it has nonnumerical characters.')
|
||||
}
|
||||
const creditCardStringLength = creditCardString.length
|
||||
if (!((creditCardStringLength >= 13) && (creditCardStringLength <= 16))) {
|
||||
if (!(creditCardStringLength >= 13 && creditCardStringLength <= 16)) {
|
||||
throw new Error(errorMessage + 'of its length.')
|
||||
}
|
||||
if (!validStartSubString.some(subString => creditCardString.startsWith(subString))) {
|
||||
if (
|
||||
!validStartSubString.some((subString) =>
|
||||
creditCardString.startsWith(subString)
|
||||
)
|
||||
) {
|
||||
throw new Error(errorMessage + 'of its first two digits.')
|
||||
}
|
||||
if (!luhnValidation(creditCardString)) {
|
||||
|
@ -8,7 +8,7 @@
|
||||
* @return {Array} Returns an array whose i-th index is the value of Z Function for text at index i
|
||||
*/
|
||||
|
||||
function zFunction (text) {
|
||||
function zFunction(text) {
|
||||
const length = text.length
|
||||
const zArray = Array(length).fill(0)
|
||||
// Initializing left and right variable to zero
|
||||
|
@ -1,22 +1,22 @@
|
||||
import { AlternativeStringArrange } from '../AlternativeStringArrange'
|
||||
|
||||
test('AlternativeStringArrange(Agrtm, loih) -> Algorithm', () => {
|
||||
const str1 = 'Agrtm'
|
||||
const str2 = 'loih'
|
||||
const res = AlternativeStringArrange(str1, str2)
|
||||
expect(res).toEqual('Algorithm')
|
||||
})
|
||||
|
||||
test('AlternativeStringArrange(JvSrp, aacit) -> JavaScript', () => {
|
||||
const str1 = 'JvSrp'
|
||||
const str2 = 'aacit'
|
||||
const res = AlternativeStringArrange(str1, str2)
|
||||
expect(res).toEqual('JavaScript')
|
||||
})
|
||||
|
||||
test('AlternativeStringArrange(abc, def) -> adbecf', () => {
|
||||
const str1 = 'abc'
|
||||
const str2 = 'def'
|
||||
const res = AlternativeStringArrange(str1, str2)
|
||||
expect(res).toEqual('adbecf')
|
||||
})
|
||||
import { AlternativeStringArrange } from '../AlternativeStringArrange'
|
||||
|
||||
test('AlternativeStringArrange(Agrtm, loih) -> Algorithm', () => {
|
||||
const str1 = 'Agrtm'
|
||||
const str2 = 'loih'
|
||||
const res = AlternativeStringArrange(str1, str2)
|
||||
expect(res).toEqual('Algorithm')
|
||||
})
|
||||
|
||||
test('AlternativeStringArrange(JvSrp, aacit) -> JavaScript', () => {
|
||||
const str1 = 'JvSrp'
|
||||
const str2 = 'aacit'
|
||||
const res = AlternativeStringArrange(str1, str2)
|
||||
expect(res).toEqual('JavaScript')
|
||||
})
|
||||
|
||||
test('AlternativeStringArrange(abc, def) -> adbecf', () => {
|
||||
const str1 = 'abc'
|
||||
const str2 = 'def'
|
||||
const res = AlternativeStringArrange(str1, str2)
|
||||
expect(res).toEqual('adbecf')
|
||||
})
|
||||
|
@ -12,9 +12,7 @@ describe('Testing checkAnagramRegex', () => {
|
||||
`(
|
||||
'expects to throw the type Error given values $inputOne and $inputTwo',
|
||||
({ inputOne, inputTwo }) => {
|
||||
expect(
|
||||
() => checkAnagramRegex(inputOne, inputTwo)
|
||||
).toThrowError()
|
||||
expect(() => checkAnagramRegex(inputOne, inputTwo)).toThrowError()
|
||||
}
|
||||
)
|
||||
|
||||
@ -102,9 +100,7 @@ describe('Testing checkAnagramMap', () => {
|
||||
`(
|
||||
'expects to throw the type Error given values $inputOne and $inputTwo',
|
||||
({ inputOne, inputTwo }) => {
|
||||
expect(
|
||||
() => checkAnagramMap(inputOne, inputTwo)
|
||||
).toThrowError()
|
||||
expect(() => checkAnagramMap(inputOne, inputTwo)).toThrowError()
|
||||
}
|
||||
)
|
||||
|
||||
|
@ -2,7 +2,9 @@ import { checkExceeding } from '../CheckExceeding'
|
||||
|
||||
describe('Testing CheckExceeding function', () => {
|
||||
it('Testing the invalid types', () => {
|
||||
expect(() => checkExceeding(Math.random())).toThrow('Argument is not a string')
|
||||
expect(() => checkExceeding(Math.random())).toThrow(
|
||||
'Argument is not a string'
|
||||
)
|
||||
expect(() => checkExceeding(null)).toThrow('Argument is not a string')
|
||||
expect(() => checkExceeding(false)).toThrow('Argument is not a string')
|
||||
expect(() => checkExceeding(false)).toThrow('Argument is not a string')
|
||||
|
@ -1,13 +1,13 @@
|
||||
import { CheckKebabCase } from '../CheckKebabCase'
|
||||
|
||||
test('CheckKebabCase(The-Algorithms) -> true', () => {
|
||||
const word = 'The-Algorithms'
|
||||
const res = CheckKebabCase(word)
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
||||
test('CheckKebabCase(The Algorithms) -> false', () => {
|
||||
const word = 'The Algorithms'
|
||||
const res = CheckKebabCase(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
import { CheckKebabCase } from '../CheckKebabCase'
|
||||
|
||||
test('CheckKebabCase(The-Algorithms) -> true', () => {
|
||||
const word = 'The-Algorithms'
|
||||
const res = CheckKebabCase(word)
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
||||
test('CheckKebabCase(The Algorithms) -> false', () => {
|
||||
const word = 'The Algorithms'
|
||||
const res = CheckKebabCase(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
|
@ -8,7 +8,9 @@ describe('Testing checkPangramRegex function', () => {
|
||||
})
|
||||
|
||||
it('"Waltz, bad nymph, for quick jigs vex." is a pangram', () => {
|
||||
expect(checkPangramRegex('Waltz, bad nymph, for quick jigs vex.')).toBe(true)
|
||||
expect(checkPangramRegex('Waltz, bad nymph, for quick jigs vex.')).toBe(
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
it('"Jived fox nymph grabs quick waltz." is a pangram', () => {
|
||||
@ -34,9 +36,9 @@ describe('Testing checkPangramRegex function', () => {
|
||||
|
||||
describe('Testing checkPangramSet function', () => {
|
||||
it('"The quick brown fox jumps over the lazy dog" is a pangram', () => {
|
||||
expect(
|
||||
checkPangramSet('The quick brown fox jumps over the lazy dog')
|
||||
).toBe(true)
|
||||
expect(checkPangramSet('The quick brown fox jumps over the lazy dog')).toBe(
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
it('"Waltz, bad nymph, for quick jigs vex." is a pangram', () => {
|
||||
@ -52,9 +54,9 @@ describe('Testing checkPangramSet function', () => {
|
||||
})
|
||||
|
||||
it('"The quick brown fox jumps over the la_y dog" is NOT a pangram', () => {
|
||||
expect(
|
||||
checkPangramSet('The quick brown fox jumps over the la_y dog')
|
||||
).toBe(false)
|
||||
expect(checkPangramSet('The quick brown fox jumps over the la_y dog')).toBe(
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
it('Throws an error if given param is not a string', () => {
|
||||
|
@ -1,19 +1,19 @@
|
||||
import { CheckPascalCase } from '../CheckPascalCase'
|
||||
|
||||
test('CheckPascalCase(TheAlgorithms) -> true', () => {
|
||||
const word = 'TheAlgorithms'
|
||||
const res = CheckPascalCase(word)
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
||||
test('CheckPascalCase(theAlgorithms) -> false', () => {
|
||||
const word = 'theAlgorithms'
|
||||
const res = CheckPascalCase(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
|
||||
test('CheckPascalCase(The Algorithms) -> false', () => {
|
||||
const word = 'The Algorithms'
|
||||
const res = CheckPascalCase(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
import { CheckPascalCase } from '../CheckPascalCase'
|
||||
|
||||
test('CheckPascalCase(TheAlgorithms) -> true', () => {
|
||||
const word = 'TheAlgorithms'
|
||||
const res = CheckPascalCase(word)
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
||||
test('CheckPascalCase(theAlgorithms) -> false', () => {
|
||||
const word = 'theAlgorithms'
|
||||
const res = CheckPascalCase(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
|
||||
test('CheckPascalCase(The Algorithms) -> false', () => {
|
||||
const word = 'The Algorithms'
|
||||
const res = CheckPascalCase(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
|
@ -1,25 +1,25 @@
|
||||
import { palindromeRearranging } from '../CheckRearrangePalindrome'
|
||||
|
||||
test('palindromeRearranging(apple) -> false', () => {
|
||||
const word = 'apple'
|
||||
const res = palindromeRearranging(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
|
||||
test('palindromeRearranging(aapplle) -> true', () => {
|
||||
const word = 'aapplle'
|
||||
const res = palindromeRearranging(word)
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
||||
test('palindromeRearranging(value) -> false', () => {
|
||||
const word = 'value'
|
||||
const res = palindromeRearranging(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
|
||||
test('palindromeRearranging(aaeccrr) -> true', () => {
|
||||
const word = 'aaeccrr'
|
||||
const res = palindromeRearranging(word)
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
import { palindromeRearranging } from '../CheckRearrangePalindrome'
|
||||
|
||||
test('palindromeRearranging(apple) -> false', () => {
|
||||
const word = 'apple'
|
||||
const res = palindromeRearranging(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
|
||||
test('palindromeRearranging(aapplle) -> true', () => {
|
||||
const word = 'aapplle'
|
||||
const res = palindromeRearranging(word)
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
||||
test('palindromeRearranging(value) -> false', () => {
|
||||
const word = 'value'
|
||||
const res = palindromeRearranging(word)
|
||||
expect(res).toBeFalsy()
|
||||
})
|
||||
|
||||
test('palindromeRearranging(aaeccrr) -> true', () => {
|
||||
const word = 'aaeccrr'
|
||||
const res = palindromeRearranging(word)
|
||||
expect(res).toBeTruthy()
|
||||
})
|
||||
|
@ -15,14 +15,33 @@ describe('Testing checkWordOccurrence', () => {
|
||||
|
||||
it('check occurrence with case sensitive', () => {
|
||||
const stringToTest = 'The quick brown fox jumps over the lazy dog'
|
||||
const expectResult = { The: 1, quick: 1, brown: 1, fox: 1, jumps: 1, over: 1, the: 1, lazy: 1, dog: 1 }
|
||||
const expectResult = {
|
||||
The: 1,
|
||||
quick: 1,
|
||||
brown: 1,
|
||||
fox: 1,
|
||||
jumps: 1,
|
||||
over: 1,
|
||||
the: 1,
|
||||
lazy: 1,
|
||||
dog: 1
|
||||
}
|
||||
|
||||
expect(checkWordOccurrence(stringToTest)).toEqual(expectResult)
|
||||
})
|
||||
|
||||
it('check occurrence with case insensitive', () => {
|
||||
const stringToTest = 'The quick brown fox jumps over the lazy dog'
|
||||
const expectResult = { the: 2, quick: 1, brown: 1, fox: 1, jumps: 1, over: 1, lazy: 1, dog: 1 }
|
||||
const expectResult = {
|
||||
the: 2,
|
||||
quick: 1,
|
||||
brown: 1,
|
||||
fox: 1,
|
||||
jumps: 1,
|
||||
over: 1,
|
||||
lazy: 1,
|
||||
dog: 1
|
||||
}
|
||||
|
||||
expect(checkWordOccurrence(stringToTest, true)).toEqual(expectResult)
|
||||
})
|
||||
|
@ -3,7 +3,9 @@ import formatPhoneNumber from '../FormatPhoneNumber'
|
||||
describe('Testing the formatPhoneNumber functions', () => {
|
||||
it('expects to throw a type error', () => {
|
||||
expect(() => formatPhoneNumber('1234567')).toThrow('Invalid phone number!')
|
||||
expect(() => formatPhoneNumber('123456text')).toThrow('Invalid phone number!')
|
||||
expect(() => formatPhoneNumber('123456text')).toThrow(
|
||||
'Invalid phone number!'
|
||||
)
|
||||
expect(() => formatPhoneNumber(12345)).toThrow('Invalid phone number!')
|
||||
})
|
||||
|
||||
|
@ -12,7 +12,7 @@ describe('LengthOfLongestSubstring', () => {
|
||||
expect(lengthOfLongestSubstring('bbbbb')).toBe(1)
|
||||
expect(lengthOfLongestSubstring('pwwkew')).toBe(3)
|
||||
expect(lengthOfLongestSubstring(' ')).toBe(1)
|
||||
expect(lengthOfLongestSubstring('abcdefghijklmnaaaaa')).toBe(13)
|
||||
expect(lengthOfLongestSubstring('abcdefghijklmnaaaaa')).toBe(14)
|
||||
})
|
||||
|
||||
it('should give zero for empty strings', () => {
|
||||
@ -20,7 +20,7 @@ describe('LengthOfLongestSubstring', () => {
|
||||
})
|
||||
|
||||
it('should be case-sensitive', () => {
|
||||
expect(lengthOfLongestSubstring('AaBbCc')).toBe(3)
|
||||
expect(lengthOfLongestSubstring('AaBbCc')).toBe(6)
|
||||
expect(lengthOfLongestSubstring('AbCdEf')).toBe(6)
|
||||
})
|
||||
})
|
||||
|
@ -7,7 +7,7 @@ describe('Testing the maxCharacter function', () => {
|
||||
})
|
||||
|
||||
it('Check the max character in string', () => {
|
||||
const theString = 'I can\'t do that'
|
||||
const theString = "I can't do that"
|
||||
const maxCharInAllCount = maxCharacter(theString)
|
||||
const maxChar = maxCharacter(theString, /\s/)
|
||||
|
||||
|
@ -2,7 +2,9 @@ import { permutate } from '../PermutateString'
|
||||
|
||||
describe('Permutate a string', () => {
|
||||
it('expects to throw an Error with an empty string', () => {
|
||||
expect(() => { permutate() }).toThrow('The arg must be a valid, non empty string')
|
||||
expect(() => {
|
||||
permutate()
|
||||
}).toThrow('The arg must be a valid, non empty string')
|
||||
})
|
||||
it('expects to permute "no" into [no, on]', () => {
|
||||
expect(['no', 'on']).toEqual(permutate('no'))
|
||||
@ -11,7 +13,19 @@ describe('Permutate a string', () => {
|
||||
expect(['esy', 'eys', 'sey', 'sye', 'yes', 'yse']).toEqual(permutate('yes'))
|
||||
})
|
||||
it('expects to permute "good" into [dgoo dogo doog gdoo godo good odgo odog ogdo ogod oodg oogd ]', () => {
|
||||
expect(['dgoo', 'dogo', 'doog', 'gdoo', 'godo', 'good', 'odgo', 'odog', 'ogdo', 'ogod', 'oodg', 'oogd'])
|
||||
.toEqual(permutate('good'))
|
||||
expect([
|
||||
'dgoo',
|
||||
'dogo',
|
||||
'doog',
|
||||
'gdoo',
|
||||
'godo',
|
||||
'good',
|
||||
'odgo',
|
||||
'odog',
|
||||
'ogdo',
|
||||
'ogod',
|
||||
'oodg',
|
||||
'oogd'
|
||||
]).toEqual(permutate('good'))
|
||||
})
|
||||
})
|
||||
|
@ -1,11 +1,16 @@
|
||||
import { ReverseStringIterative, ReverseStringIterativeInplace } from '../ReverseString'
|
||||
import {
|
||||
ReverseStringIterative,
|
||||
ReverseStringIterativeInplace
|
||||
} from '../ReverseString'
|
||||
|
||||
describe('ReverseStringIterative', () => {
|
||||
it('expects to reverse a simple string', () => {
|
||||
expect(ReverseStringIterative('reverse')).toEqual('esrever')
|
||||
expect(ReverseStringIterative('some')).toEqual('emos')
|
||||
expect(ReverseStringIterative('string')).toEqual('gnirts')
|
||||
expect(ReverseStringIterative('The Algorithms Javascript')).toEqual('tpircsavaJ smhtiroglA ehT')
|
||||
expect(ReverseStringIterative('The Algorithms Javascript')).toEqual(
|
||||
'tpircsavaJ smhtiroglA ehT'
|
||||
)
|
||||
})
|
||||
|
||||
it('expects to reverse a string with spaces in between', () => {
|
||||
@ -25,7 +30,9 @@ describe('ReverseStringIterative', () => {
|
||||
`(
|
||||
'expects to throw a type error given a value that is $input',
|
||||
({ input }) => {
|
||||
expect(() => ReverseStringIterative(input)).toThrow('The given value is not a string')
|
||||
expect(() => ReverseStringIterative(input)).toThrow(
|
||||
'The given value is not a string'
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
|
@ -19,6 +19,8 @@ describe('Testing the reverseWords function', () => {
|
||||
it('expects to reverse words to return a joined word', () => {
|
||||
expect(reverseWords('I Love JS')).toBe('JS Love I')
|
||||
expect(reverseWords('Hello World')).toBe('World Hello')
|
||||
expect(reverseWords('The Algorithms Javascript')).toBe('Javascript Algorithms The')
|
||||
expect(reverseWords('The Algorithms Javascript')).toBe(
|
||||
'Javascript Algorithms The'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
@ -14,26 +14,48 @@ describe('Validate credit card number', () => {
|
||||
})
|
||||
it('should throw an error on non-numeric character in given credit card number', () => {
|
||||
const nonNumericCCNumbers = ['123ABCDEF', 'ABCDKDKD', 'ADS232']
|
||||
nonNumericCCNumbers.forEach(nonNumericCC => expect(() => validateCreditCard(nonNumericCC)).toThrow(
|
||||
`${nonNumericCC} is an invalid credit card number because ` + 'it has nonnumerical characters.'
|
||||
))
|
||||
nonNumericCCNumbers.forEach((nonNumericCC) =>
|
||||
expect(() => validateCreditCard(nonNumericCC)).toThrow(
|
||||
`${nonNumericCC} is an invalid credit card number because ` +
|
||||
'it has nonnumerical characters.'
|
||||
)
|
||||
)
|
||||
})
|
||||
it('should throw an error on credit card with invalid length', () => {
|
||||
const ccWithInvalidLength = ['41111', '4111111111111111111111']
|
||||
ccWithInvalidLength.forEach(invalidCC => expect(() => validateCreditCard(invalidCC)).toThrow(
|
||||
`${invalidCC} is an invalid credit card number because ` + 'of its length.'
|
||||
))
|
||||
ccWithInvalidLength.forEach((invalidCC) =>
|
||||
expect(() => validateCreditCard(invalidCC)).toThrow(
|
||||
`${invalidCC} is an invalid credit card number because ` +
|
||||
'of its length.'
|
||||
)
|
||||
)
|
||||
})
|
||||
it('should throw an error on credit card with invalid start substring', () => {
|
||||
const ccWithInvalidStartSubstring = ['12345678912345', '23456789123456', '789123456789123', '891234567891234', '912345678912345', '31345678912345', '32345678912345', '33345678912345', '38345678912345']
|
||||
ccWithInvalidStartSubstring.forEach(invalidCC => expect(() => validateCreditCard(invalidCC)).toThrow(
|
||||
`${invalidCC} is an invalid credit card number because ` + 'of its first two digits.'
|
||||
))
|
||||
const ccWithInvalidStartSubstring = [
|
||||
'12345678912345',
|
||||
'23456789123456',
|
||||
'789123456789123',
|
||||
'891234567891234',
|
||||
'912345678912345',
|
||||
'31345678912345',
|
||||
'32345678912345',
|
||||
'33345678912345',
|
||||
'38345678912345'
|
||||
]
|
||||
ccWithInvalidStartSubstring.forEach((invalidCC) =>
|
||||
expect(() => validateCreditCard(invalidCC)).toThrow(
|
||||
`${invalidCC} is an invalid credit card number because ` +
|
||||
'of its first two digits.'
|
||||
)
|
||||
)
|
||||
})
|
||||
it('should throw an error on credit card with luhn check fail', () => {
|
||||
const invalidCCs = ['411111111111111', '371211111111111', '49999999999999']
|
||||
invalidCCs.forEach(invalidCC => expect(() => validateCreditCard(invalidCC)).toThrow(
|
||||
`${invalidCC} is an invalid credit card number because ` + 'it fails the Luhn check.'
|
||||
))
|
||||
invalidCCs.forEach((invalidCC) =>
|
||||
expect(() => validateCreditCard(invalidCC)).toThrow(
|
||||
`${invalidCC} is an invalid credit card number because ` +
|
||||
'it fails the Luhn check.'
|
||||
)
|
||||
)
|
||||
})
|
||||
})
|
||||
|
@ -18,7 +18,11 @@ describe('Validation of an Email Address', () => {
|
||||
})
|
||||
|
||||
it('expects to throw a type error', () => {
|
||||
expect(() => { validateEmail('') }).toThrow('Email Address String Null or Empty.')
|
||||
expect(() => { validateEmail(null) }).toThrow('Email Address String Null or Empty.')
|
||||
expect(() => {
|
||||
validateEmail('')
|
||||
}).toThrow('Email Address String Null or Empty.')
|
||||
expect(() => {
|
||||
validateEmail(null)
|
||||
}).toThrow('Email Address String Null or Empty.')
|
||||
})
|
||||
})
|
||||
|
Reference in New Issue
Block a user