A collection of my responses to the Intermediate Algorithm Scripting problems under freeCodeCamp's JavaScript Algorithms and Data Structures course.
File names correspond to the accompanying function names for each problem.
A collection of my responses to the Intermediate Algorithm Scripting problems under freeCodeCamp's JavaScript Algorithms and Data Structures course.
File names correspond to the accompanying function names for each problem.
function addTogether() { | |
const [first, second] = arguments; | |
if (typeof (first) !== 'number') return undefined; | |
if (second === undefined) { | |
return (second) => addTogether(first, second); | |
} | |
if (typeof (second) !== 'number') return undefined; | |
return first + second; | |
} | |
console.log( | |
addTogether(2, 3), // 5 | |
addTogether(23, 30), // 53 | |
addTogether(5)(7), // 12 | |
addTogether('https://www.youtube.com/watch?v=dQw4w9WgXcQ'), // undefined | |
addTogether(2, '3'), // undefined | |
addTogether(2)([3]), // undefined | |
addTogether('2', 3) // undefined | |
) |
function binaryAgent(str) { | |
const bValues = str.split(' ') | |
const dValues = bValues.map(e => { | |
return parseInt(e, 2) | |
}) | |
const sentence = dValues.map(e => { | |
return String.fromCharCode(e) | |
}) | |
return sentence.join('') | |
} | |
console.log(binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111")) |
// Convert the characters &, <, >, " (double quote), and ' (apostrophe), in a string to their corresponding HTML entities. | |
function convertHTML(str) { | |
/* | |
let chars = str.split(''); | |
for(let i = 0; i < chars.length; i++) { | |
switch(chars[i]) { | |
case "&": | |
chars[i] = "&"; | |
break; | |
case "<": | |
chars[i] = "<"; | |
break; | |
case ">": | |
chars[i] = ">"; | |
break; | |
case '"': | |
chars[i] = """; | |
break; | |
case "'": | |
chars[i] = "'"; | |
break; | |
} | |
} | |
return chars.join(''); | |
*/ | |
// using map | |
const symbols = { | |
"&": "&", | |
"<": "<", | |
">": ">", | |
'"': """, | |
"'": "'" | |
} | |
return str | |
.split('') | |
.map(e => symbols[e] || e) | |
.join('') | |
} | |
console.log( | |
convertHTML("Dolce & Gabbana") + "\n", // Dolce & Gabbana | |
convertHTML("Hamburgers < Pizza < Tacos") + "\n", // Hamburgers < Pizza < Tacos | |
convertHTML("Sixty > twelve") + "\n", // Sixty > twelve | |
convertHTML('Stuff in "quotation marks"') + "\n", // Stuff in "quotation marks" | |
convertHTML("Schindler's List") + "\n", // Schindler's List | |
convertHTML("<>") + "\n", // <> | |
convertHTML("abc") // abc | |
) |
// Remove values in arr that are same values as ...vals | |
// ...vals copies arguments from that index into array 'vals' | |
function destroyer(arr, ...vals) { | |
// for element in arr, return it if not in vals | |
return arr.filter(e => !vals.includes(e)) | |
} | |
destroyer([1, 2, 3, 1, 2, 3], 2, 3)) // yields [1, 1] |
// Compare two arrays and return the symmetric difference in new array | |
function diffArray(arr1, arr2) { | |
return arr1 | |
.concat(arr2) // merge arr1 and arr2 | |
// using includes | |
.filter(e => !arr1.includes(e) || !arr2.includes(e)) | |
// for each element in merged array, find element that is not in arr1 or arr2 | |
// using indexOf | |
.filter(e => arr1.indexOf(e) === -1 || arr2.indexOf(e) === -1) | |
// for each element in merged array, return element that has indexOf value of -1 in arr1 or arr2 | |
} | |
diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]) // yields [ 4 ] |
function dropElements(arr, func) { | |
// using shift | |
/* let length = arr.length; | |
for (let i = 0; i < length; i++) { | |
if (func(arr[0])) { | |
break; | |
} else { | |
arr.shift(); | |
} | |
} | |
return arr; */ | |
// using slice | |
let sliceAt = arr.findIndex(func); | |
return arr.slice(sliceAt >= 0 ? sliceAt : arr.length); | |
} | |
console.log( | |
dropElements([1, 2, 3], function (n) { return n < 3; }), | |
dropElements([0, 1, 0, 1], function (n) { return n === 1; }), | |
dropElements([1, 2, 3], function (n) { return n > 0; }), | |
dropElements([1, 2, 3, 4], function (n) { return n > 5; }), | |
dropElements([1, 2, 3, 7, 4], function (n) { return n > 3; }), | |
dropElements([1, 2, 3, 9, 2], function (n) { return n > 2; }) | |
) |
/* | |
Find the missing letter in the passed letter range and return it. | |
If all letters are present in the range, return undefined. | |
*/ | |
function fearNotLetter(str) { | |
var code = str.charCodeAt(0); | |
for (var i = 0; i < str.length; i++) { | |
if (str.charCodeAt(i) !== code + i) { | |
return String.fromCharCode(code + i); | |
} | |
} | |
return undefined; | |
} | |
console.log(fearNotLetter("abce")) // should return "d". | |
console.log(fearNotLetter("abcdefghjklmno")) // should return "i". | |
console.log(fearNotLetter("stvwx")) // should return "u". | |
console.log(fearNotLetter("bcdf")) // should return "e". | |
console.log(fearNotLetter("abcdefghijklmnopqrstuvwxyz")) // should return undefined. |
const Person = function(firstAndLast) { | |
let fullName = firstAndLast; | |
this.getFirstName = function() { | |
return fullName.split(' ')[0] | |
}; | |
this.getLastName = function() { | |
return fullName.split(' ')[1] | |
}; | |
this.getFullName = function() { | |
return fullName.split(' ')[0] + ' ' + fullName.split(' ')[1]; | |
}; | |
this.setFirstName = function(first) { | |
fullName = first + ' ' + fullName.split(' ')[1]; | |
}; | |
this.setLastName = function(last) { | |
fullName = fullName.split(' ')[0] + ' ' + last; | |
}; | |
this.setFullName = function(firstAndLast) { | |
fullName = firstAndLast.split(' ')[0] + ' ' + firstAndLast.split(' ')[1]; | |
}; | |
}; | |
// testing | |
const bob = new Person('Bob Ross'); | |
console.log( | |
'\n', | |
bob.getFirstName(), '\n', | |
bob.getLastName(), '\n', | |
bob.getFullName(), '\n', | |
bob.setFirstName('Haskell'), '\n', | |
bob.setLastName('Curry'), '\n', | |
bob.setFullName('Haskell Curry'), '\n', | |
bob.getFullName() | |
) |
function orbitalPeriod(arr) { | |
const GM = 398600.4418; | |
const earthRadius = 6367.4447; | |
return arr.map(({ name, avgAlt }) => { | |
const averageOrbit = earthRadius + avgAlt; | |
const orbitalPeriod = Math.round(2*Math.PI*Math.sqrt(Math.pow(averageOrbit, 3)/GM)); | |
return { name, orbitalPeriod }; | |
}) | |
} | |
console.log( | |
orbitalPeriod([{ name: "sputnik", avgAlt: 35873.5553 }]), // yields [{name: "sputnik", orbitalPeriod: 86400}] | |
orbitalPeriod([{ name: "iss", avgAlt: 413.6 }, { name: "hubble", avgAlt: 556.7 }, { name: "moon", avgAlt: 378632.553 }]) | |
// yields [{name : "iss", orbitalPeriod: 5557}, {name: "hubble", orbitalPeriod: 5734}, {name: "moon", orbitalPeriod: 2377399}] | |
) |
/* | |
Pairs of DNA strands consist of protein base pairs. Base pairs are represented by the characters AT and CG, which form building blocks of the DNA double helix. | |
The DNA strand is missing the pairing element. Write a function to match the missing base pairs for the provided DNA strand. For each character in the provided string, | |
find the base pair character. Return the results as a 2d array. | |
For example, for the input GCG, return [["G", "C"], ["C","G"], ["G", "C"]] | |
The character and its pair are paired up in an array, and all the arrays are grouped into one encapsulating array. | |
*/ | |
function pairElement(str) { | |
let result = [] | |
let strand = str.split('') | |
strand.map(e => { | |
if (e === 'A') { | |
result.push(['A', 'T']) | |
} else if (e === 'T') { | |
result.push(['T', 'A']) | |
} else if (e === 'G') { | |
result.push(['G', 'C']) | |
} else if (e === 'C') { | |
result.push(['C', 'G']) | |
} | |
}) | |
return result | |
} | |
console.log(pairElement("GCG")) |
function searchAndReplace(str, before, after) { | |
let search = new RegExp(before, "gi"); | |
if(before.charAt(0) === before.charAt(0).toUpperCase()) { | |
return str.replace(search, after.charAt(0).toUpperCase() + after.slice(1)); | |
} else if(after.charAt(0) === after.charAt(0).toUpperCase()) { | |
return str.replace(search, after.charAt(0).toLowerCase() + after.slice(1)); | |
} else { | |
return str.replace(search, after); | |
} | |
} | |
console.log(searchAndReplace("I think we should look up there", "up", "Down")) |
/* Find the smallest common multiple of the provided parameters that can be evenly divided by both, | |
* as well as by all sequential numbers in the range between these parameters. | |
*/ | |
function smallestCommons(arr) { | |
const [min, max] = arr.sort((a, b) => (a - b)) | |
const range = Array(max - min + 1) | |
.fill(0) | |
.map((_, i) => i + min); | |
const upperBound = range.reduce((prod, curr) => { | |
return prod * curr; | |
}) | |
for (let mult = max; mult <= upperBound; mult += max) { | |
const divisible = range.every((value) => mult % value === 0); | |
if (divisible) { | |
return mult; | |
} | |
} | |
} | |
console.log( | |
"\n", | |
smallestCommons([1, 5]), "\n", // 60 | |
smallestCommons([5, 1]), "\n", // 60 | |
smallestCommons([2, 10]), "\n", // 2520 | |
smallestCommons([1, 13]), "\n", // 360360 | |
smallestCommons([23, 18]) // 6056820 | |
) |
function spinalCase(str) { | |
let newStr = str.replace(/([a-z])([A-Z])/g, '$1 $2'); | |
newStr = newStr.replace(/_|(\s+)/g, '-').toLowerCase(); | |
return newStr; | |
} | |
console.log(spinalCase('This Is Spinal Tap')) | |
console.log(spinalCase("thisIsSpinalTap")) | |
console.log(spinalCase("The_Andy_Griffith_Show")) | |
console.log(spinalCase("Teletubbies say Eh-oh")) | |
console.log(spinalCase("AllThe-small Things")) |
function steamrollArray(arr) { | |
let result = []; | |
// using for loop | |
// for (let i = 0; i < arr.length; i++) { | |
// if(Array.isArray(arr[i])) { | |
// result.push(...steamrollArray(arr[i])); | |
// } else { | |
// result.push(arr[i]); | |
// } | |
// } | |
// return result; | |
// using filter | |
arr.filter(e => { | |
if (!Array.isArray(e)) { | |
result.push(e) | |
} else { | |
result.push(...steamrollArray(e)) | |
} | |
}) | |
return result; | |
} | |
console.log( | |
steamrollArray([[["a"]], [["b"]]]), | |
steamrollArray([1, [2], [3, [[4]]]]), | |
steamrollArray([1, [], [3, [[4]]]]), | |
steamrollArray([1, {}, [3, [[4]]]]) | |
) |
// Sum all numbers between numbers in array (inclusive). | |
// Lowest number is not always at first index. | |
function sumAll(arr) { | |
let sum = 0; | |
for(let i = Math.min(...arr); i <= Math.max(...arr); i++) sum += i | |
return sum; | |
} | |
sumAll([4, 1]) // yields 10 |
// Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num. | |
function sumOddFibs(num) { | |
let sum = 0; | |
let previous = 0; | |
let current = 1; | |
while (current <= num) { | |
if (current % 2 !== 0) { | |
sum += current; | |
} | |
current += previous; | |
previous = current - previous; | |
} | |
return sum; | |
} | |
console.log( | |
sumOddFibs(10), "\n", // 10 | |
sumOddFibs(1000), "\n", // 1785 | |
sumOddFibs(4000000), "\n", // 4613732 | |
sumOddFibs(4), "\n", // 5 | |
sumOddFibs(75024), "\n", // 60696 | |
sumOddFibs(75025) // 135721 | |
); |
// sum all prime numbers <= num | |
function sumPrimes(num) { | |
// check if numbers from i to sqrt(num) are prime | |
function isPrime(num) { | |
for (let i = 2; i <= Math.sqrt(num); i++) { | |
if (num % i === 0) return false; | |
} | |
return true; | |
} | |
// if isPrime, sum += i | |
let sum = 0; | |
for (let i = 2; i <= num; i++) { | |
if(isPrime(i)) sum += i; | |
} | |
return sum; | |
} | |
console.log( | |
sumPrimes(10), // 17 | |
sumPrimes(977) // 73156 | |
); |
/* if a word begins with consonant, move it or the consanant cluster to the end of the word and add "ay" | |
* if a word begins with vowel, add "way" to the end of the word | |
*/ | |
function translatePigLatin(str) { | |
let vowels = ['a', 'e', 'i', 'o', 'u']; | |
let consonants = ['b', 'c', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'v', 'w', 'x', 'y', 'z']; | |
// check if the first letter is a vowel | |
if (vowels.includes(str[0])) { | |
return str + "way"; | |
} | |
// if a word begins with a consonant, move it or the consanant cluster to the end of the word and add "ay" | |
else if (consonants.includes(str[0])) { | |
let i = 0; | |
while (consonants.includes(str[i])) { | |
i++; | |
} | |
return str.substring(i) + str.substring(0, i) + "ay"; | |
} | |
} | |
console.log( | |
translatePigLatin("consonant"), | |
translatePigLatin("california"), | |
translatePigLatin("paragraphs"), | |
translatePigLatin("glove"), | |
translatePigLatin("algorithm"), | |
translatePigLatin("eight"), | |
translatePigLatin("schwartz"), | |
translatePigLatin("rhythm"), | |
) |
/* | |
* Write a function that takes two or more arrays and returns a new array of unique values in the order of the original provided arrays. | |
* Constraints: elements cannot repeat and must maintain original order | |
*/ | |
function uniteUnique(arr) { | |
// can use 'arguments' to access all arrays | |
let buffer = []; | |
for(let i = 0; i < arguments.length; i++) { | |
for(let j = 0; j < arguments[i].length; j++) { | |
if(!buffer.includes(arguments[i][j])) { | |
buffer.push(arguments[i][j]); | |
} | |
} | |
} | |
return buffer; | |
} | |
console.log( | |
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1]), // [1, 3, 2, 5, 4] | |
uniteUnique([1, 2, 3], [5, 2, 1]), // [1, 2, 3, 5] | |
uniteUnique([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]), // [1, 2, 3, 5, 4, 6, 7, 8] | |
uniteUnique([1, 3, 2], [5, 4], [5, 6]), // [1, 3, 2, 5, 4, 6] | |
uniteUnique([1, 3, 2, 3], [5, 2, 1, 4], [2, 1]) // [1, 3, 2, 5, 4] | |
) |
// Look through collection and return all objects that match source | |
function whatIsInAName(collection, source) { | |
return collection.filter(e => { | |
for(let i in source) if(source[i] !== e[i]) return false | |
return true | |
}) | |
} | |
whatIsInAName( | |
[ | |
{ first: "Romeo", last: "Montague" }, | |
{ first: "Mercutio", last: null }, | |
{ first: "Tybalt", last: "Capulet" } | |
], | |
{ last: "Capulet" })) | |
// yields [ { first: 'Tybalt', last: 'Capulet' } ] |