Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Intermediate Algorithm Scripting

Intermedate Algorithm Scripting

FreeCodeCamp - Bonfire series

My FreeCodeCamp profile [http://freecodecamp.com/rlynjb]


  1. [Bonfire: Sum All Numbers in a Range] (#file-sum-all-numbers-in-a-range-js)
  2. [Bonfire: Diff Two Arrays] (#file-diff-two-arrays-js)
  3. [Bonfire: Roman Numeral Converter] (#file-roman-numeral-converter-js)
  4. [Bonfire: Where art thou] (#file-where-art-thou-js)
  5. [Bonfire: Search and Replace] (#file-search-and-replace-js)
  6. [Bonfire: Pig Latin] (#file-pig-latin-js)
  7. [Bonfire: DNA Pairing] (#file-dna-pairing-js)
  8. [Bonfire: Missing letters] (#file-missing-letters-js)
  9. [Bonfire: Boo who] (#file-boo-who-js)
  10. [Bonfire: Sorted Union] (#file-sorted-union-js)
  11. [Bonfire: Convert HTML Entities] (#file-convert-html-entities-js)
  12. [Bonfire: Spinal Tap Case] (#file-spinal-tap-case-js)
  13. [Bonfire: Sum All Odd Fibonacci Numbers] (#file-sum-all-odd-fibonacci-numbers-js)
  14. [Bonfire: Sum All Primes] (#file-sum-all-primes-js)
  15. [Bonfire: Smallest Common Multiple] (#file-smallest-common-multiple-js)
  16. [Bonfire: Finders Keepers] (#file-finders-keepers-js)
  17. [Bonfire: Drop it] (#file-drop-it-js)
  18. [Bonfire: Steamroller] (#file-steamroller-js)
  19. [Bonfire: Binary Agents] (#file-binary-agents-js)
  20. [Bonfire: Everything Be True] (#file-everything-be-true-js)
  21. [Bonfire: Arguments Optional] (#file-arguments-optional-js)
/*
Create a function that sums two arguments together. If only one argument is provided, then return a function that expects one argument and returns the sum.
For example, add(2, 3) should return 5, and add(2) should return a function.
Calling this returned function with a single argument will then return the sum:
var sumTwoAnd = add(2);
sumTwoAnd(3) returns 5.
If either argument isn't a valid number, return undefined.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Closures
Arguments object
*/
function add(x) {
// checks if its only 1 arg and if string
if (arguments.length === 1 && typeof arguments[0] !== 'number') return undefined;
if (arguments.length >= 2) {
// iterate through arguments and sum
total = 0;
for( var i in arguments ) {
if (typeof arguments[i] !== 'number') return undefined;
total += arguments[i];
}
return total;
} else {
return function(y) {
if (typeof y !== 'number') return undefined;
return x + y;
};
}
}
var sum2And = add(2);
sum2And(3);
/*
Return an English translated sentence of the passed binary string.
The binary string will be space separated.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
String.charCodeAt()
String.fromCharCode()
*/
function binaryAgent(str) {
str = str.split(' ');
binaryToDecimal = 0;
decipher = '';
// loop through group of binaries
for (i=0; i<str.length; i++) {
var strLength = str[i].length;
// loop through each binary number
for (f=0; f<str[i].length; f++) {
var strToNum = parseInt(str[i][f]),
expo = parseInt(strLength -= 1);
// convert binary to decimal, only with 1s
if (strToNum === 1) {
binaryToDecimal += Math.pow(2, expo);
}
}
decipher += String.fromCharCode(binaryToDecimal);
// reset this to 0 per each group binary
binaryToDecimal = 0;
//console.log(binaryToDecimal, String.fromCharCode(binaryToDecimal));
//break;
}
console.log(decipher);
return decipher;
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
/*
Check if a value is classified as a boolean primitive. Return true or false.
Boolean primitives are true and false.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Boolean Objects
*/
function boo(bool) {
// What is the new fad diet for ghost developers? The Boolean.
console.log(typeof bool, bool)
if (typeof bool == 'boolean') {
return true;
}
if (typeof bool == 'string') {
return false;
}
if (typeof bool == 'object') {
return false;
}
if (typeof bool == 'function') {
return false;
}
if (typeof bool == 'number') {
return false;
}
}
boo(false);
/*
Convert the characters "&", "<", ">", '"' (double quote), and "'" (apostrophe), in a string to their corresponding HTML entities.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
RegExp
HTML Entities
*/
function convert(str) {
re = /[^A-Za-z0-9_\s]/g;
str = str.replace(re, function(match) {
switch (match) {
case '&':
return '&amp;';
case '<':
return '&lt;';
case '>':
return '&gt;';
case '"':
return '&quot;';
case '\'':
return '&apos;';
}
});
return str;
}
convert("<>");
/*
Compare two arrays and return a new array with any items not found in both of the original arrays.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Comparison Operators
Array.slice()
Array.filter()
Array.indexOf()
Array.concat()
*/
function diff(arr1, arr2) {
var newArr = [];
filterArr1 = arr1.filter(function(val) {
console.log('arr1', val, 'arr2', arr2.indexOf(val));
return arr2.indexOf(val) === -1;
});
filterArr2 = arr2.filter(function(val) {
console.log('arr2', val, 'arr1', arr1.indexOf(val));
return arr1.indexOf(val) === -1;
});
console.log(filterArr1, filterArr2);
newArr = filterArr1.concat(filterArr2);
// Same, same; but different.
res = newArr;
return res;
}
diff([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);
/*
The DNA strand is missing the pairing element. Take each character, get its pair, and return the results as a 2d array.
Base pairs are a pair of AT and CG. Match the missing element to the provided character.
Return the provided character as the first element in each 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.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Array.push()
String.split()
*/
/* NOTE: a clearer tutorial on DNA pairing
https://www.sophia.org/tutorials/base-pairing-of-nitrogenous-bases
*/
function pair(str) {
var splitStr = str.split(''),
DNAPaired = [],
result = [];
for (i=0; i<splitStr.length; i++) {
if (splitStr[i] === 'A') {
DNAPaired = [splitStr[i], 'T'];
}
if (splitStr[i] === 'T') {
DNAPaired = [splitStr[i], 'A'];
}
if (splitStr[i] === 'C') {
DNAPaired = [splitStr[i], 'G'];
}
if (splitStr[i] === 'G') {
DNAPaired = [splitStr[i], 'C'];
}
result.push(DNAPaired);
}
console.log(result);
return result;
}
pair("ATCGA");
/*
Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Arguments object
Array.shift()
*/
function drop(arr, func) {
// Drop them elements.
/*for (i=0; i<arr.length; i++) {
if (!func(arr[0])) {
arr.shift();
} else {
break;
}
}*/
arr = arr.filter(func);
return arr;
}
drop([1, 2, 3, 4], function(n) {return n < 3; });
/*
Check if the predicate (second argument) is truthy on all elements of a collection (first argument).
Remember, you can access object properties through either dot notation or [] notation.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
*/
function every(collection, pre) {
// Is everyone being true?
var itemsPresent = 0;
for (var g in collection) {
if (collection[g].hasOwnProperty(pre) && Boolean(collection[g][pre])) {
itemsPresent++;
}
}
console.log(itemsPresent, collection.length);
if (itemsPresent === collection.length) {
return true;
} else {
return false;
}
//return pre;
}
every([{"user": "Tinky-Winky", "sex": "male", "age": 0}, {"user": "Dipsy", "sex": "male", "age": 3}, {"user": "Laa-Laa", "sex": "female", "age": 5}, {"user": "Po", "sex": "female", "age": 4}], "age");
/*
Create a function that looks through an array (first argument) and returns the first element in the array that passes a truth test (second argument).
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Array.filter()
*/
function find(arr, func) {
var num = 0;
as = arr.filter(function(v, i) {
if (func(v)) {
return v;
}
});
num = as[0];
return num;
}
find([1, 2, 3, 4], function(num){ return num % 2 === 0; });
/*
Find the missing letter in the passed letter range and return it.
If all letters are present in the range, return undefined.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
String.charCodeAt()
String.fromCharCode()
*/
function fearNotLetter(str) {
var strSplit = str.split(''),
numRange = [],
numRangeUnique = [];
// get char code for each char
for (i=0; i<strSplit.length; i++) {
var charCode = str.charCodeAt(i);
numRange.push(charCode);
//console.log(charCode, String.fromCharCode(charCode));
}
// find missing number in range
var tempNum = numRange[0];
numRangeUnique.push(tempNum);
for (k=0; k<numRange.length; k++) {
// checks if tempNum is at its lowest num and compare
if (k === 0 && numRange[k] === tempNum) {
tempNum++;
} else {
tempNum++;
}
numRangeUnique.push(tempNum);
}
console.log('num range', numRange);
console.log('numunique', numRangeUnique);
// retrieve code for missing letter
for (j=0; j<numRange.length; j++) {
for (h=0; h<numRangeUnique.length; h++) {
console.log(numRange[j], numRangeUnique[h]);
// remove value in numRangeUnique
if (numRange[j] === numRangeUnique[h]) {
console.log('match');
numRange.splice(j, 1);
} else {
console.log('unique', numRangeUnique[h]);
return String.fromCharCode(numRangeUnique[h]);
}
if (numRange[j] === undefined) {
return undefined;
console.log('end search');
//break
}
}
}
}
fearNotLetter("bcd");
/*
Translate the provided string to pig latin.
Pig Latin takes the first consonant (or consonant cluster) of an English word, moves it to the end of the word and suffixes an "ay".
If a word begins with a vowel you just add "way" to the end.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Array.indexOf()
Array.push()
Array.join()
String.substr()
String.split()
*/
function translate(str) {
var vowStr = [],
conStr = [],
conStr1 = [],
splitStr = str.split('');
if (str[0] === 'e' || str[0] === 'a') {
for (var i=0; i<splitStr.length; i++) {
if (splitStr[i] === 'e' || splitStr[i] === 'a') {
vowStr.push(str);
vowStr.push('way');
return str = vowStr.join('');
break;
}
}
}
if (str[0] === 'c' || str[0] === 'p' || str[0] === 'g' || str[0] === 'l') {
for (var i=0; i<splitStr.length; i++) {
if (splitStr[i] === 'c' || splitStr[i] === 'p' || splitStr[i] === 'g' || splitStr[i] === 'l') {
conStr.push(splitStr[i]);
} else {
conStr1.push(str.substr(i));
return str = conStr1.join('') + conStr.join('') + 'ay';
break;
}
}
}
/*for (var i=0; i<splitStr.length; i++) {
if (splitStr[i] === 'e' || splitStr[i] === 'a') {
vowStr.push(str);
vowStr.push('way');
return str = vowStr.join('');
break;
}
if (splitStr[i] === 'c' || splitStr[i] === 'p' || splitStr[i] === 'g' || splitStr[i] === 'l') {
conStr.push(splitStr[i]);
} else {
conStr1.push(str.substr(i));
return str = conStr1.join('') + conStr.join('') + 'ay';
break;
}
}*/
}
translate("algorithm");
/*
Convert the given number into a roman numeral.
All roman numerals answers should be provided in upper-case.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Roman Numerals
Array.splice()
Array.indexOf()
Array.join()
*/
function convert(num) {
var splitNum = num.toString().split(''),
tens = splitNum[0],
ones = splitNum[1],
newNum = [];
// Checks if num is 1s
if (num < 10) {
if (num == 5) {
newNum.push('V')
}
// Checks 9
if (num == 9) {
newNum.push('IX');
}
}
// Checks if num is 10s
if (num > 10) {
for (var i=0; i<tens; i++) {
newNum.push('X')
}
// Checks 6,7,8
if (ones > 5 && ones < 8) {
newNum.push('V');
for (var k=5; k<ones; k++) {
newNum.push('I');
}
}
// Checks 4,3,2,1
if (ones < 5) {
for (var g=0; g<ones; g++) {
newNum.push('I');
}
}
// Checks 9
if (ones == 9) {
newNum.push('IX');
}
}
//console.log(newNum.join(''));
return newNum.join('');
}
convert(5);
/*
Perform a search and replace on the sentence using the arguments provided and return the new sentence.
First argument is the sentence to perform the search and replace on.
Second argument is the word that you will be replacing (before).
Third argument is what you will be replacing the second argument with (after).
NOTE: Preserve the case of the original word when you are replacing it. For example if you mean to replace the word "Book" with the word "dog", it should be replaced as "Dog"
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Array.splice()
String.replace()
Array.join()
*/
function myReplace(str, before, after) {
var splitStr = str.split(' ');
for (var i=0; i<splitStr.length; i++) {
// check if string matches before, check if string is Uppercase
if (splitStr[i].match(before) && splitStr[i].match(/[A-Z]/) && i !== 0) {
var afterUpper = after[0].toUpperCase() + after.slice(1);
splitStr.splice(i, 1, afterUpper);
}
if (splitStr[i].match(before)) {
splitStr.splice(i, 1, after);
}
}
console.log(splitStr.join(' '));
//console.log(newStr.join(' '));
return splitStr.join(' ');
}
myReplace("He is Sleeping on the couch", "Sleeping", "sitting");
/*
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.
The range will be an array of two numbers that will not necessarily be in numerical order.
e.g. for 1 and 3 - find the smallest common multiple of both 1 and 3 that is evenly divisible by all numbers between 1 and 3.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Smallest Common Multiple
*/
function smallestCommons(arr) {
var max = Math.max.apply(null, arr),
min = Math.min.apply(null, arr) - 1,
newArr = [];
for (i=max; i>min; i--) {
newArr.push(i);
}
// Variables needed declared outside the loops.
var quot = 0;
var loop = 1;
var n;
// run code while n is not the same as the array length.
do {
quot = newArr[0] * loop * newArr[1];
for (n = 2; n < newArr.length; n++) {
if (quot % newArr[n] !== 0) {
break;
}
}
loop++;
} while (n !== newArr.length);
return quot;
}
smallestCommons([1,5]);
/*
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.
In other words, all values present from all arrays should be included in their original order, but with no duplicates in the final array.
The unique numbers should be sorted by their original order, but the final array should not be sorted in numerical order.
Check the assertion tests for examples.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Arguments object
Array.reduce()
*/
function unite(arr1, arr2, arr3) {
// collect all arguments
var arr = [];
for (i=0; i<arguments.length; i++) {
arr.push(arguments[i]);
}
// concat arguments into an arr
var concatArrs = arr.reduce(function(a, b) {
return a.concat(b);
});
keepUnique = concatArrs.filter(function(v, i, a) {
console.log(i, a.indexOf(v), v);
return i === a.indexOf(v);
});
//console.log(concatArrs);
//console.log('result', keepUnique);
return keepUnique;
}
unite([1, 3, 2], [5, 2, 1, 4], [2, 1]);
/*
Convert a string to spinal case. Spinal case is all-lowercase-words-joined-by-dashes.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
RegExp
String.replace()
*/
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
re = /[A-Z\s_]/g;
// if str has no whitespace and special chars
console.log(!/[\s-_]/.test(str));
str = str.replace(re, function(val) {
// checks if val is uppercase, has no whitespace
//console.log(val == (val.toUpperCase() && val.match(/\S/g)));
if (!/[\s-_]/.test(str)) {
return '-' + val.toLowerCase();
}
switch (val) {
case ' ':
return '-';
case '_':
return '-';
}
return val.toLowerCase();
});
return str;
}
spinalCase('thisIsSpinalTap');
/*
Flatten a nested array. You must account for varying levels of nesting.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Array.isArray()
*/
function steamroller(arr) {
// I'm a steamroller, baby
var newArr = [],
checkIfArray = function(v) {
if (!Array.isArray(v)) {
newArr.push(v);
} else {
for (var i in v) {
checkIfArray(v[i]);
}
}
};
arr.forEach(checkIfArray);
return newArr;
}
steamroller([1, [2], [3, [[4]]]]);
/*
We'll pass you an array of two numbers. Return the sum of those two numbers and all numbers between them.
The lowest number will not always come first.
Here are some helpful links:
Math.max()
Math.min()
Array.reduce()
*/
function sumAll(arr) {
maxNum = Math.max(arr[0], arr[1]),
minNum = Math.min(arr[0], arr[1]),
newArr = [];
for (var i=minNum; i<maxNum; i++) {
// list all numbers bet min and max numbers
newArr.push(i);
// its seems like its not generating last number so we'll
// need to detect of it reaches last number
(i == maxNum-1) ? newArr.push(i + 1) : '';
}
total = newArr.reduce(function(a, b, c, d) {
return a + b;
});
return total;
}
sumAll([1, 4]);
/*
Return the sum of all odd Fibonacci numbers up to and including the passed number if it is a Fibonacci number.
The first few numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8, and each subsequent number is the sum of the previous two numbers.
As an example, passing 4 to the function should return 5 because all the odd Fibonacci numbers under 4 are 1, 1, and 3.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
Remainder
*/
function sumFibs(num) {
var fib = [],
prev = 1,
curr = 1,
sum = 0;
for (i=0; i<num; i++) {
if (i === 0) fib[i] = prev;
if (i === 1) fib[i] = curr;
if (i >= 2) fib[i] = fib[i-2] + fib[i-1];
if (fib[i] % 2 !== 0) {
if (fib[i] > num) break;
sum += fib[i];
console.log('odd', i, fib[i]);
}
}
console.log('sum', sum);
num = sum;
return num;
}
sumFibs(1000);
/*
Sum all the prime numbers up to and including the provided number.
A prime number is defined as having only two divisors, 1 and itself. For example, 2 is a prime number because it's only divisible by 1 and 2. 1 isn't a prime number, because it's only divisible by itself.
The provided number may not be a prime.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.
Here are some helpful links:
For Loops
Array.push()
*/
// Note: https://www.gorkahernandez.com/blog/fcc-bonfire-series-131-sum-all-prime/
function sumPrimes(num) {
result = 2;
// sum all prime numbers and get result
for (i=3; i<=num; i+=2) {
if (isPrime(i)) result += i;
console.log(i);
}
num = result;
return num;
}
// This function detects prime numbers
// it already consists of algorithm thats been proven and optimized
// Checks number if prime or not
function isPrime(number) {
// this function will fail if number is 0 or 1
// so we add a check below
if (number <= 1) return false;
for (var i = 2; i < number/2; i++) {
if (number % i === 0) return false;
}
return true;
}
sumPrimes(10);
/*
Make a function that looks through an array of objects (first argument) and returns an array of all objects that have matching property and value pairs (second argument). Each property and value pair of the source object has to be present in the object from the collection if it is to be included in the returned array.
For example, if the first argument is [{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], and the second argument is { last: "Capulet" }, then you must return the third object from the array (the first argument), because it contains the property and it's value, that was passed on as the second argument.
Remember to use Read-Search-Ask if you get stuck. Write your own code.
Here are some helpful links:
Global Object
Object.hasOwnProperty()
Object.keys()
*/
function where(collection, source) {
var arr = [];
for (var i in collection) {
if (collection.hasOwnProperty(i)) {
var g = collection[i].last;
//console.log(g);
if (g == source.last) {
arr.push(collection[i]);
}
}
}
// What's in a name?
return arr;
}
where([{ first: 'Romeo', last: 'Montague' }, { first: 'Mercutio', last: null }, { first: 'Tybalt', last: 'Capulet' }], { last: 'Capulet' });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment