Skip to content

Instantly share code, notes, and snippets.

@Ovicakov
Last active May 3, 2021 17:41
Show Gist options
  • Save Ovicakov/338234f4087e5f078033ba73b5295ae8 to your computer and use it in GitHub Desktop.
Save Ovicakov/338234f4087e5f078033ba73b5295ae8 to your computer and use it in GitHub Desktop.
Freecodecamp JavaScript algorithms and data structures certification
/*** intermediate algorithm challenge n° 4 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/wherefore-art-thou
***/
function whatIsInAName(collection, source) {
const srcKeys = Object.keys(source)
return collection.filter((obj) => {
return srcKeys.every((key) => {
return obj.hasOwnProperty(key) && obj[key] === source[key]
})
})
}
whatIsInAName([
{ first: "Romeo", last: "Montague" },
{ first: "Mercutio", last: null },
{ first: "Tybalt", last: "Capulet" }
], { last: "Capulet" });
// OR
const whatIsInAName = (list, reference) => {
const pairsToCheck = Object.entries(reference)
return list.filter(entry => {
return pairsToCheck.every(([key, value]) => entry[key] === value)
})
}
whatIsInAName([
{ id: 1, "apple": 1, "bat": 2 },
{ id: 2, "apple": 1 },
{ id: 3, "apple": 1, "bat": 2, "cookie": [2, 8] }
], { "apple": 1, "cookie": [2, 8] })
/*** intermediate algorithm challenge n° 8 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/dna-pairing
***/
function pairElement(str) {
const ATCG = [['A', 'T'], ['C', 'G']]
const splitedString = str.split('')
const getSecondLetter = (letter, array) => {
const currentArr = array.find(item => item.find(v => v === letter))
return currentArr.find(l => l !== letter)
}
const pairLetters = splitedString.reduce((acc, current) => {
const addLetter = getSecondLetter(current, ATCG)
const total = [current, addLetter]
return [...acc, total]
}, [])
return pairLetters
}
pairElement("ATCGA");
/*** intermediate algorithm challenge n° 9 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/missing-letters
***/
function fearNotLetter(str) {
const alpha = "abcdefghijklmnopqrstuvwxyz"
const splittedAlpha = alpha.split('')
const splittedStr = str.split('')
const firstStrLetter = splittedStr[0]
const lastStrLetter = splittedStr[splittedStr.length - 1]
const findTheIndex = (letter) => letter === firstStrLetter
const findTheLastIndex = (letter) => letter === lastStrLetter
const firstIndex = splittedAlpha.findIndex(findTheIndex)
const lastIndex = splittedAlpha.findIndex(findTheLastIndex)
const extractStrFromAlpha = splittedAlpha.slice(firstIndex, lastIndex)
return extractStrFromAlpha.find(v => {
if (splittedStr.includes(v) === false) return v
})
}
fearNotLetter("abce");
/*** intermediate algorithm challenge n° 10 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities
***/
function uniteUnique(arr, ...rest) {
const uniqueArr = [arr, ...rest].flat()
const removeDuplicate = (array) => {
return array.filter((value, index) => array.indexOf(value) === index)
}
return removeDuplicate(uniqueArr);
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
// OR
function uniteUnique(arr, ...rest) {
const uniqueArr = arr.concat(...rest)
return [...new Set(uniqueArr)]
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]);
/*** intermediate algorithm challenge n° 11 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/convert-html-entities
***/
function convertHTML(str) {
const cleanString = (str) => {
return str
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g,'&apos;')
}
return cleanString(str)
}
convertHTML("Dolce & Gabbana");
// OR
function convertHTML(str) {
const htmlEntities = {
'&': '&amp;',
'<': "&lt;",
'>': "&gt;",
'"': "&quot;",
"'": "&apos;",
}
return str
.split('')
.map(letter => htmlEntities[letter] || letter)
.join('')
}
convertHTML("Dolce & Gabbana");
/*** intermediate algorithm challenge n° 12 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers
***/
function sumFibs(num) {
let result = 0, prevNumber = 0, currNumber = 1
let arr = [currNumber]
while (currNumber <= num) {
arr.push(result)
result = prevNumber + currNumber
prevNumber = currNumber
currNumber = result
}
return arr
.filter(value => value %2 !== 0)
.reduce((accum, curr) => accum + curr)
}
console.log(sumFibs(75024))
/*** intermediate algorithm challenge n° 13 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-primes
***/
function sumPrimes(num) {
const arr = []
const isAPrimeNumber = (number) => {
let array = []
for (let i = 1; i <= number; i++) {
Number.isInteger(number / i) ? array.push(i) : null
}
return array.length === 2
}
for (let i = 1; i <= num; i++) {
isAPrimeNumber(i) ? arr.push(i) : null
}
return arr.reduce((accum, curr) => accum + curr)
}
sumPrimes(10);
/*** intermediate algorithm challenge n° 15 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it
***/
function dropElements(arr, func) {
const indexArr = []
arr.map((number, index) => {
func(number) ? indexArr.push(index) : null
})
return indexArr.length === 0 ? indexArr : arr.slice(indexArr[0])
}
dropElements([1, 2, 3, 4], function(n) {return n > 5;})
/*** intermediate algorithm challenge n° 16 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/steamroller
***/
function steamrollArray(arr) {
return arr.reduce((acc, curr) => {
return acc.concat(Array.isArray(curr) ? steamrollArray(curr) : curr)
}, [])
}
steamrollArray([1, [2], [3, [[4]]]]);
/*** intermediate algorithm challenge n° 17 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/binary-agents
***/
function binaryAgent(str) {
return str
.split(' ')
.map(letter => String.fromCharCode(parseInt(letter, 2)))
.join('')
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
/*** intermediate algorithm challenge n° 18 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/everything-be-true
***/
function truthCheck(collection, pre) {
return collection.every(obj => obj[pre])
}
truthCheck([
{"user": "Tinky-Winky", "sex": "male"},
{"user": "Dipsy", "sex": "male"},
{"user": "Laa-Laa", "sex": "female"},
{"user": "Po", "sex": "female"}
], "sex");
/*** intermediate algorithm challenge n° 19 :
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/make-a-person
***/
function addTogether(a, b) {
const isANumber = (num) => typeof num === 'number'
if (!isANumber(a) || (b && !isANumber(b))) return undefined
if (isANumber(a) && isANumber(b)) return a + b
return function(c) {
if (isANumber(c)) return a + c
}
}
addTogether(2, "3")
addTogether(5)(7)
/*
Projet 1 : https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/palindrome-checker
Palyndrome checker
*/
function palindrome(str) {
const sanitizedString = str.replace(/[^a-zA-Z0-9]/g, '')
const oldString = sanitizedString
const newString = sanitizedString.split('').reverse().join('')
return oldString.toLowerCase() === newString.toLowerCase()
}
palindrome("0_0 (: /-\ :) 0-0")
palindrome("A man, a plan, a canal. Panama")
palindrome("five|\_/|four")
/*
Projet 2 : https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/roman-numeral-converter
Roman numeral converter
*/
function convertToRoman(num) {
const romanNumerals = {
1: 'I',
5: 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M'
}
const romanPairs = Object.entries(romanNumerals)
const getRomanNumeralsFromNumber = (number) => {
const letters = []
const keys = []
const romanNumeralKeys = Object.keys(romanNumerals)
const getTheAdditionNumber = romanNumeralKeys.find(key => key.length === String(number).length)
romanPairs.find(([key, value]) => {
// handle 1...
if (Number(key) === number) letters.push(romanNumerals[key])
// handle 4..., 9...
if (number + Number(getTheAdditionNumber) === Number(key)) {
letters.push(romanNumerals[getTheAdditionNumber] + value)
}
// handle 6...
else if (number - Number(getTheAdditionNumber) === Number(key)) {
letters.push(value + romanNumerals[getTheAdditionNumber])
}
// handle 2..., 3..., 7..., 8...
else if (number > key && key.length === String(number).length) {
keys.push(key)
const firstLetter = romanNumerals[keys[keys.length - 1]]
const getFirstNumberFromNumber = String(number).split('')[0]
const repeatedValues = getFirstNumberFromNumber < 5
? value.concat(firstLetter.repeat(getFirstNumberFromNumber - 1))
: value.concat(romanNumerals[keys[0]].repeat(getFirstNumberFromNumber - 5))
letters.push(repeatedValues)
}
})
return letters[letters.length - 1]
}
return String(num).split('').reverse().map((value, index) => {
const splittedValue = value !== '0' ? value.concat(String(0).repeat(index)) : null
return splittedValue !== null ? getRomanNumeralsFromNumber(Number(splittedValue)) : ''
}).reverse().join('')
}
convertToRoman(2014)
/*
Projet 3 : https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/caesars-cipher
Caesars Cipher
*/
function rot13(str) {
const alphabet = {
'A': 'N',
'B': 'O',
'C': 'P',
'D': 'Q',
'E': 'R',
'F': 'S',
'G': 'T',
'H': 'U',
'I': 'V',
'J': 'W',
'K': 'X',
'L': 'Y',
'M': 'Z',
}
const letters = []
const keysObject = Object.keys(alphabet)
const valuesObject = Object.values(alphabet)
const string = str.split('').map((letter) => {
if (keysObject.includes(letter)) {
letters.push(alphabet[letter])
}
if (valuesObject.includes(letter)) {
Object.entries(alphabet).map(([key, value]) => {
if (value === letter) {
letters.push(key)
}
})
}
if (!!letter.match(/[.,:!?\s]/g)) letters.push(letter)
})
return letters.join('')
}
rot13("GUR DHVPX OEBJA SBK WHZCF BIRE GUR YNML QBT.")
/*
Projet 4 : https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/telephone-number-validator
Telephone number validator
*/
function telephoneCheck(str) {
const regex = /^((1\s?)?(\(\d{3}\)|\d{3})(-|\s)?(\d{3})(-|\s)?(\d{4}))$/g
return regex.test(str)
}
telephoneCheck('555-555-5555')
telephoneCheck('(555)555-5555')
telephoneCheck('(555) 555-5555')
/*
projet 5 : https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/javascript-algorithms-and-data-structures-projects/cash-register
Cash Register
*/
function checkCashRegister(price, cash, cid) {
const currencyAmount = {
'PENNY': 0.01,
'NICKEL': 0.05,
'DIME': 0.1,
'QUARTER': 0.25,
'ONE': 1,
'FIVE': 5,
'TEN': 10,
'TWENTY': 20,
'ONE HUNDRED': 100,
}
const keyValueCurrency = Object.entries(currencyAmount)
const valuesCurrency = Object.values(currencyAmount)
const change = cash - price
const splittedChange = Number(String(change).split('.'))
const reverseArray = cid.reverse()
const status = {
INSUFFICIENT: "INSUFFICIENT_FUNDS",
CLOSED: "CLOSED",
OPEN: "OPEN",
}
function getTheDrawerDetails(arr) {
return arr.reduce((acc, [key, value]) => {
const getDrawerDetails = Math.round((value / currencyAmount[key]) * 100 / 100)
return [...acc, [key, getDrawerDetails]]
}, [])
}
function getTheDrawerTotal(arr) {
let total
return arr.reduce((acc, [key, value]) => {
total = acc + value
return total * 100 / 100
}, 0)
}
function getTheRemain(value, currencyValue, remain) {
let total = 0
const getMaximum = value / currencyValue
for (let i = 0; i <= remain && i <= getMaximum * currencyValue; i += currencyValue) {
if (total > value) return
total = i
}
return total
}
function getChange() {
let totalRemaining = change
return cid.reduce((acc, [key, value]) => {
if (value === change) return [...acc]
const roundedTotal = Math.round(totalRemaining * 100) / 100
let result = getTheRemain(value, currencyAmount[key], roundedTotal)
totalRemaining -= result
if (result === 0) return [...acc]
return [...acc, [key, result]]
}, [])
}
switch (true) {
case (getTheDrawerTotal(cid) > change && !(getTheDrawerTotal(getChange()) < change)):
return {
status: status.OPEN,
change: getChange()
}
case (getTheDrawerTotal(cid) > change && getTheDrawerTotal(getChange()) < change):
return {
status: status.INSUFFICIENT,
change: []
}
case (getTheDrawerTotal(cid) < change):
return {
status: status.INSUFFICIENT,
change: []
}
case (getTheDrawerTotal(cid) === change):
return {
status: status.CLOSED,
change: cid.reverse()
}
default:
console.log('oupssss')
}
}
console.log(checkCashRegister(3.26, 100, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.1], ["QUARTER", 4.25], ["ONE", 90], ["FIVE", 55], ["TEN", 20], ["TWENTY", 60], ["ONE HUNDRED", 100]]))
console.log(checkCashRegister(19.5, 20, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment