{{ message }}

Instantly share code, notes, and snippets.

# rlynjb/01 FreeCodeCamp - Bonfire: Intermediate Algorithm Scripting.markdown

Last active Sep 14, 2018
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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 '&'; case '<': return '<'; case '>': return '>'; case '"': return '"'; case '\'': return '''; } }); return str; } convert("<>");
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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]);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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");
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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; });
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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 5 && ones < 8) { newNum.push('V'); for (var k=5; k
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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]);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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');
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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]]]]);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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= 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);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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);
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 /* 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' });