Skip to content

Instantly share code, notes, and snippets.

@abhisekp
Last active February 1, 2023 10:43
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save abhisekp/ec330ea725247bbf9e8e to your computer and use it in GitHub Desktop.
Save abhisekp/ec330ea725247bbf9e8e to your computer and use it in GitHub Desktop.
Solutions to FreeCodeCamp Challenges - http://j.mp/abhisekpFCCSolns
function meetBonfire(argument) {
// Good luck!
console.log("you can read this function's argument in the developer tools", argument);
return true;
}
meetBonfire("You can do this!");
function telephoneCheck(str) {
// Good luck!
// I'm feeling lucky today!
return /^(1)?(((?:\s*\(\s*)(\d{3})(?:\s*\)\s*))|((\s*|-)\d{3}(\s*|-)))(\d{3})(\s*-?\s*)(\d{4})$/.test(str);
}
telephoneCheck("555-555-5555");
function reverseString(str) {
return str.split("").reverse().join("");
}
reverseString('hello');
function factorialize(num) {
return (num < 2) ? 1 : (num * factorialize(num - 1));
}
factorialize(5);
function factorialize(num) {
var fact = 1;
while(num) { fact *= num--; }
return fact;
}
factorialize(5);
var romanPair = {
1: 'I',
5: 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M'
};
// all bases as number sorted in ascending order
var romanBases = Object.keys(romanPair).sort(function (a, b) {
return a - b;
}).map(function (base) {
return Number(base);
});
// console.log('romanBases:', romanBases);
var minRomanBase = Math.min.apply(null, romanBases);
var maxRomanBase = Math.max.apply(null, romanBases);
function convert(num) {
// console.log('num:', num);
if (num < minRomanBase || num > maxRomanBase) {
if (num === 0) {
return 'Zero (0) was discovered later by Aryabhata (Indian Mathematician).';
}
else if (num > maxRomanBase) {
return 'Romans were too tired to extend their number system.'
}
return 'You should definitely consider using the modern decimal number system.';
}
if (romanPair[num]) {
return romanPair[num];
}
var baseInset = 1,
tempBase = 1;
romanBases.forEach(function (base, i) {
if (num > base) {
// check if the base is either 1, 10, 100 or 1000
if (Math.log10(base) % 1 === 0) {
// find the baseInset value
baseInset = base;
}
if (romanBases[i + 1] - num <= baseInset) {
// assign the tempBase to the next romanBase
tempBase = romanBases[i + 1];
}
else {
// assign the tempBase to the current romanBase
tempBase = base;
}
}
});
// console.log('baseInset:', baseInset);
// console.log('tempBase:', tempBase);
var diff = 0,
romanNum;
// if number is > a roman tempBase
if (num > tempBase) {
diff = num - tempBase;
// console.log('diff:', diff);
romanNum = convert(tempBase) + convert(diff);
}
else { // fixme
diff = num - (tempBase - baseInset);
// console.log('diff:', diff);
romanNum = convert(baseInset) + convert(tempBase) + (diff ? convert(diff) : '');
}
return romanNum;
}
convert(36);
function palindrome(str) {
str = str.toLowerCase().replace(/[\W_]/g, '');
for(var i = 0, len = str.length - 1; i < len/2; i++) {
if(str[i] !== str[len-i]) {
return false;
}
}
return true;
}
palindrome("eye");
function palindrome(str) {
return (str = str.toLowerCase().replace(/\W|_/g, '')) === str.split('').reverse().join('');
}
palindrome("0_0 (: /-\\ :) 0-0");
function where(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function (obj) {
// return a Boolean value for filter callback using reduce method
return srcKeys.reduce(function (res, key) {
// reduce to Boolean value to be returned by reduce method
return obj.hasOwnProperty(key) && obj[key] === source[key];
}, false);
});
}
where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' });
function where(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function (obj) {
for(var i = 0; i < srcKeys.length; i++) {
// check if obj in collection doesn't have the key
// or if it does have the key,
// then check if the property value doesn't match the value in source
if(!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) {
return false;
}
}
return true;
});
}
where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' });
function where(collection, source) {
// "What's in a name? that which we call a rose
// By any other name would smell as sweet.”
// -- by William Shakespeare, Romeo and Juliet
var srcKeys = Object.keys(source);
// filter the collection
return collection.filter(function (obj) {
// return a Boolean value for `filter` method
return srcKeys.every(function (key) {
// reduce to Boolean value to be returned for `every` method
return obj.hasOwnProperty(key) && obj[key] === source[key];
});
});
}
where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' });
function findLongestWord(str) {
var maxWordLength = 0,
words = str.split(' ');
for(var i = 0, len = words.length; i < len; i++) {
if(words[i].length > maxWordLength) {
maxWordLength = words[i].length;
}
}
return maxWordLength;
}
findLongestWord('The quick brown fox jumped over the lazy dog');
function findLongestWord(str) {
var maxWordLength = 0,
words = str.split(' ');
maxWordLength = words.reduce(function(max, curr) {
return curr.length > max ? curr.length : max;
}, 0);
return maxWordLength;
}
findLongestWord('The quick brown fox jumped over the lazy dog');
function findLongestWord(str) {
return Math.max(...str.split(' ').map(word => word.length));
}
findLongestWord("The quick brown fox jumped over the lazy dog");
function myReplace(str, before, after) {
var replaced = after;
function replacer(before, after) {
return after.split('').map(function (afterCh, i) {
var beforeCh = before[i];
if (i >= before.length) {
return afterCh;
}
if (beforeCh >= 'a' && beforeCh <= 'z') {
return afterCh.toLowerCase();
}
else if (beforeCh >= 'A' && beforeCh <= 'Z') {
return afterCh.toUpperCase();
}
return afterCh;
}).join('');
}
replaced = str.replace(before, replacer(before, after));
return replaced;
}
myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
// https://repl.it/BRTQ/4
function findLongestWord(str) {
var maxWordLength = 0,
words = str.split(' ');
words.forEach(function(curr) {
if(curr.length > maxWordLength) {
maxWordLength = curr.length;
}
});
return maxWordLength;
}
findLongestWord('The quick brown fox jumped over the lazy dog');
function titleCase(str) {
str = str.toLowerCase();
var words = str.split(' ');
for(var i = 0, len = words.length; i < len; i++) {
words[i] = words[i][0].toUpperCase() + words[i].substr(1);
}
str = words.join(' ');
return str;
}
titleCase("I'm a little tea pot");
function titleCase(str) {
str = str.toLowerCase();
var words = str.split(' ');
str = words.map(function (word) {
return word[0].toUpperCase() + word.substr(1);
}).join(' ');
return str;
}
titleCase("I'm a little tea pot");
function titleCase(str) {
return str.replace(/(\w)([\w']*)/g, function (match, $1, $2){
return $1.toUpperCase() + $2.toLowerCase();
});
}
titleCase("I'm a little tea pot");
function titleCase(str) {
return str.toLowerCase().replace(/(?: |^)[a-z]/g, (L) => L.toUpperCase());
}
titleCase("I'm a little tea pot");
function find(array, cb) {
/* ES6 Array.prototype.find available */
if(typeof Array.prototype.find !== 'undefined') {
return array.find(cb);
}
// console.log('ES6 Array.prototype.find Unavailable');
for(var index = 0; index < array.length; index++) {
var curr = array[index];
var found = cb(curr, index, array);
if(found) {
var value = array[index];
return value;
}
}
}
function nextInCircularArray(array, index) {
// console.log('\nindex:', index);
// console.log('Given Array:', array);
var nextIndex = (index+1) % array.length;
// console.log('nextIndex:', nextIndex);
return array[nextIndex];
}
function pair(DNAstr) {
function findPair(pairs, DNA) {
return find(pairs, function (pair) {
return pair.indexOf(DNA) !== -1;
});
}
var pairs = [
['A', 'T'],
['G', 'C']
];
return [].map.call(DNAstr, function (DNA) {
var pair = [DNA];
console.log('DNA:', DNA);
var foundPair = findPair(pairs, DNA);
console.log('> foundPair:', foundPair);
var otherDNA = nextInCircularArray(foundPair, foundPair.indexOf(DNA));
console.log('> otherDNA:', otherDNA);
pair.push(otherDNA);
return pair;
});
}
pair("ATCGA");
function pair(str) {
var pairs = {A:'T', T: 'A', C: 'G', G: 'C'};
return [].map.call(str, function(dna){
return [dna, pairs[dna]];
});
}
pair("ATCGA");
function largestOfFour(arr) {
// You can do this!
for(var i = 0; i < arr.length; i++) {
var max = arr[i][0];
for(var j = 1; j < arr.length; j++) {
if(arr[i][j] > max) {
max = arr[i][j];
}
}
arr[i] = max;
}
return arr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
function largestOfFour(arr) {
// You can do this!
// Yes, I can. :P
return arr.map(Function.apply.bind(Math.max, null));
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
function end(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
// "I find my own luck!" -- AbhisekP.
return target === str.substr(str.length - target.length);
}
end('Bastian', 'n');
function end(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
// "I find my own luck!" -- AbhisekP.
return new RegExp(target + '$').test(str);
}
end('Bastian', 'n');
function end(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
// "I find my own luck!" -- AbhisekP.
return str.endsWith(target);
}
end('Bastian', 'n');
function end(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
// "I find my own luck!" -- AbhisekP.
return str.lastIndexOf(target) === str.length - target.length;
}
end('Bastian', 'n');
function fearNotLetter(str) {
var startCode = str.charCodeAt(0);
var endCode = str.charCodeAt(str.length-1);
if(endCode - startCode + 1 === str.length) {
return;
}
var missing = '';
for(var codeIndex = startCode; codeIndex !== endCode; codeIndex++) {
var currChar = String.fromCharCode(codeIndex);
if(str.indexOf(currChar) === -1) {
missing += currChar;
}
}
return missing;
}
fearNotLetter("abce");
function boo(bool) {
// What is the new fad diet for ghost developers? The Boolean.
return typof bool === 'boolean';
}
boo(null);
function repeat(str, num) {
// repeat after me
// am i in class 2 or something?
var repeated = '';
while(num-- > 0) {
repeated += str;
}
return repeated;
}
repeat('abc', 3);
function repeat(str, num) {
// repeat after me
// am i in class 2 or something?
return num <= 0 ? '': str.repeat(num);
}
repeat('abc', 3);
function convert(str) {
'use strict';
var htmlEntities = {
'\'': '&apos;',
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
get get() {
return function (entity) {
return this[entity];
};
},
get toString() {
return function () {
return Object.keys(this).join('');
}
}
};
Object.defineProperties(htmlEntities, {
get: {
enumerable: false
},
toString: {
enumerable: false
}
});
var re = new RegExp('[' + htmlEntities + ']', 'g');
return str.replace(re, function (entity) {
return htmlEntities.get(entity);
});
}
convert('Dolce & Gabbana');
function truncate(str, num) {
// Clear out that junk in your trunk
// trunk is loaded
if(str.length > num) {
if(num <= 3) {
return str.substr(0, num) + '...';
}
return str.substr(0, num-3) + '...';
}
return str;
}
truncate('A-tisket a-tasket A green and yellow basket', 11);
function truncate(str, num) {
// Clear out that junk in your trunk
// trunk is loaded
return str.length > num ? num <= 3 ? str.substr(0, num) + '...': str.substr(0, num-3) + '...' : str;
}
truncate('A-tisket a-tasket A green and yellow basket', 11);
this.myNamespace = {};
(function (namespace, window, undefined) {
var htmlEntities = {
'\'': '&apos;',
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
get get() {
return function (entity) {
return this[entity];
};
},
get toString() {
return function () {
return Object.keys(this).join('');
};
}
};
Object.defineProperties(htmlEntities, {
get: {
enumerable: false
},
toString: {
enumerable: false
}
});
namespace.htmlEntities = htmlEntities;
})(myNamespace, this);
function convert(str) {
'use strict';
var re = new RegExp('[' + myNamespace.htmlEntities + ']', 'g');
return str.replace(re, myNamespace.htmlEntities.get.bind(myNamespace.htmlEntities));
}
convert('Dolce & Gabbana');
function chunk(arr, size) {
// Break it up
// It's already broken :(
arr = arr.slice();
var arr2 = [];
for(var i = 0, len = arr.length; i < len; i+=size) {
arr2.push(arr.slice(0, size));
arr = arr.slice(size);
}
return arr2;
}
chunk(['a', 'b', 'c', 'd'], 2);
function slasher(arr, howMany) {
// it doesn't always pay to be first
// well, now my head is chopped off >:(
return arr.splice(0, howMany) && arr;
}
slasher([1, 2, 3], 2);
function sumFibs(num) {
// Fibonacci is life. It's everywhere
var sum = 0,
last = 0,
fib = 1;
for(var curr = 1; fib <= num; fib = last + curr, last = curr, curr = fib) {
if(fib % 2) {
sum += fib;
}
// console.log(last, curr, fib);
}
return sum;
}
sumFibs(4);
function sumFibs(num) {
// Fibonacci is life. It's everywhere
var sum = 0,
last = 0,
curr = 1,
fib = curr;
while(fib <= num) {
if(fib % 2) {
sum += fib;
}
// console.log(last, curr, fib);
fib = last + curr;
last = curr;
curr = fib;
}
return sum;
}
sumFibs(4);
function bouncer(arr) {
// Don't show a false ID to this bouncer.
// I've a hammer fist.
return arr.filter(Boolean);
}
bouncer([7, 'ate', '', false, 9]);
function bouncer(arr) {
// Don't show a false ID to this bouncer.
// I've a hammer fist.
var filtered = [];
for(var i = 0; i < arr.length; i++) {
if(Boolean(arr[i])) {
filtered.push(arr[i]);
}
}
return filtered;
}
bouncer([7, 'ate', '', false, 9]);
function destroyer(arr) {
// Remove all the values
// I don't like the emptiness :P
var args = [].slice.call(arguments, 1);
return arr.filter(function (el) {
for(var i = 0; i < args.length; i++) {
if(args[i] === el) {
return false;
}
}
return true;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
function destroyer(arr) {
// Remove all the values
// I don't like the emptiness :P
// grab the other args
var args = [].slice.call(arguments, 1);
// filter the given array
return arr.filter(function (el) {
// return a Boolean true if args elements doesn't match el
return args.reduce(function (res, curr) {
return res && curr !== el;
}, true);
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
function destroyer(arr) {
// Remove all the values
// I don't like the emptiness :P
// grab the other args
var args = [].slice.call(arguments, 1);
// filter the given array
return arr.filter(function (el) {
// return elements not in the args
return args.indexOf(el) === -1;
});
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
function destroyer(arr, ...args) {
return arr.filter((el) => !args.includes(el))
}
destroyer([1, 2, 3, 1, 2, 3], 2, 3);
function find(arr, func) {
// Find me if you can
return arr.filter(func)[0];
}
find([1, 2, 3, 4], function(num){ return num % 2 === 0; });
function where(arr, num) {
// Find my place in this sorted array.
// Why? Are you lost?
return arr.reduce((pos, curr) => num <= curr ? pos : pos + 1, 0);
}
where([40, 60], 50);
function drop(arr, func) {
// Drop them elements.
// They're not eggs!
for(var i = 0; i < arr.length; i++) {
if(func(arr[i])) {
return arr.slice(i);
}
}
return [];
}
drop([1, 2, 3], function(n) {return n < 3; });
function drop(arr, func) {
// Drop them elements.
// They're not eggs!
'use strict';
for(let el of arr) {
if(func(el)) {
return arr.slice(arr.indexOf(el));
}
}
return [];
}
drop([1, 2, 3], function(n) {return n < 3; });
function rot13(str) { // LBH QVQ VG!
return str.replace(/[A-Z]/g, (L) => String.fromCharCode(65 + L.charCodeAt(0) % 26));
}
rot13("SERR PBQR PNZC");
function addTogether(a, b) {
return typeof a === 'number' ?
(arguments.length < 2
? addTogether.bind(null, a)
: typeof b === 'number' ? a + b : undefined
) : undefined;
}
addTogether('2',3);
addTogether(0, 3);
addTogether(0, 0);
addTogether(0.5, 0.5);
addTogether(0.5, 2.5);
addTogether(-2.5, 0);
addTogether(0, '0');
function addTogether(a, b) {
if (typeof a !== 'number') {
return;
}
if (arguments.length < 2) {
return addTogether.bind(null, a);
}
if (typeof b !== 'number') {
return;
}
return a + b;
}
function binaryAgent(str) {
return str.replace(/\d+\s?/g, val => String.fromCodePoint(parseInt(val, 2)))
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111")
function binaryAgent(str) {
return String.fromCodePoint.apply(
null,
str.split(' ').map(val => parseInt(val, 2))
)
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111")
function diffArray(arr1, arr2) {
// Same, same; but different.
return arr1.filter(el => !arr2.includes(el))
.concat(arr2.filter(el => !arr1.includes(el)));
}
diff([1, 2, 3, 5], [1, 2, 3, 4, 5]);
function truthCheck(collection, pre) {
// Is everyone being true?
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");
function checkCashRegister(price, cash, cid) {
const currenciesVal = {
'ONE HUNDRED': 100,
TWENTY: 20,
TEN: 10,
FIVE: 5,
ONE: 1,
QUARTER: 0.25,
DIME: 0.1,
NICKEL: 0.05,
PENNY: 0.01,
}
let remains = +(cash - price).toFixed(2)
const total = +(cid.reduce((sum, cashes) => sum + cashes[1], 0)).toFixed(2)
if (remains === total) {
return 'Closed'
}
// Here is your change, ma'am.
return cid.reverse()
.reduce((returnVal, currCID, idx) => {
const type = currCID[0] // currency type
const val = currenciesVal[type] // currency value
const avail = currCID[1] // currency available in drawer
// amount to spend for this currency in drawer
const usage = Math.floor(Math.min(avail, remains) / val) * val
// remaining amount after deducing the used amount
remains = +(remains - usage).toFixed(2)
// if this is the last cash drawer and there are still change left
if ((idx === cid.length - 1) && remains) {
return 'Insufficient Funds'
}
// if currency used, then add it to value
if (usage) {
returnVal.push([type, usage])
}
return returnVal
}, [])
}
console.log(
checkCashRegister(19.50, 20.00, [
["PENNY", 1.01],
["NICKEL", 2.05],
["DIME", 3.10],
["QUARTER", 4.25],
["ONE", 90.00],
["FIVE", 55.00],
["TEN", 20.00],
["TWENTY", 60.00],
["ONE HUNDRED", 100.00]
])
)
function mutation(arr) {
// change is the only constant in universe
return arr[1].toLowerCase().split('').every(letter => arr[0].toLowerCase().includes(letter));
}
mutation(['hello', 'hey']); // false
mutation(['hello', 'helloy']); // false
mutation(['hello', 'yellow']); // false
function mutation(arr) {
// change is the only constant in universe
var test = arr[1].toLowerCase(),
target = arr[0].toLowerCase();
for(var i = 0; i < test.length; i++) {
if(target.indexOf(test[i]) < 0) {
return false;
}
}
return true;
}
mutation(['hello', 'hey']);
function translatePigLatin(str) {
return /^[aeiou]/.test(str)
? str + 'way'
: str.replace(/([^aeiou]+)(.+)/, '$2$1ay')
}
translatePigLatin("consonant")
function lookUpProfile(firstName, prop) {
const foundContact = contacts.find(contact => contact.firstName === firstName)
if (!foundContact) return "No such contact"
return foundContact.hasOwnProperty(prop)
? foundContact[prop]
: "No such property"
}
lookUpProfile("Akira", "likes")
function updateRecords(id, prop, value) {
// store the collection with corresponding collection id
const col = collection[id]
// check if value is empty/blank
if(value === '') {
// delete the property entirely
delete col[prop]
return collection // exit the function
}
// check if prop is tracks
if (prop === 'tracks') {
// check if prop exists and push the value at the end
if (col[prop]) col[prop].push(value)
// otherwise, assign a new array with value as 1st element
else col[prop] = [value]
return collection // exit the function
}
// if code has reached till this point, means
// value must not be blank
// and prop must not be tracks
// so assign the prop with the value
col[prop] = value
return collection // exit the function
}
function uniteUnique(...arrs) {
return [].concat(...arrs).filter(
(val, idx, currArr) => currArr.indexOf(val) === idx
)
}
uniteUnique([1, 3, 2], [5, 2, 1, 4], [2, 1])
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
return str.replace(
/[_\s](\w)|(?=[A-Z])/g,
(s, w) => w ? '-'+w : '-'
).replace(/^-/, '').toLowerCase()
}
spinalCase('This Is Spinal Tap')
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
return str.split(/\s|_|(?=[A-Z])/).join('-').toLowerCase()
}
spinalCase('This Is Spinal Tap')
function steamrollArray (arr) {
return Array.isArray(arr)
? [].concat.apply([], arr.map(steamrollArray))
: arr
}
steamrollArray([1, [2], [3, [[4]]]])
function sumAll([firstNum, lastNum]) {
// Buckle up everything to one!
// Using Arithmetic Progression summing formula
// https://en.wikipedia.org/wiki/Arithmetic_progression#Sum
return (Math.abs(lastNum - firstNum) + 1) * (firstNum + lastNum) / 2;
}
sumAll([10, 1]); // 55
function sym(...arrays) {
// Same, Same
// But different
return arrays.reduce((symDiff, arr) =>
symDiff.concat(arr)
.filter((val, idx, theArr) =>
theArr.indexOf(val) === idx && !(symDiff.includes(val) && arr.includes(val))
)
)
}
sym([1, 2, 3], [5, 2, 1, 4]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment