Skip to content

Instantly share code, notes, and snippets.

@adamthewan
Last active March 4, 2016 03:22
Show Gist options
  • Save adamthewan/da17786a74e96cdc8ee0 to your computer and use it in GitHub Desktop.
Save adamthewan/da17786a74e96cdc8ee0 to your computer and use it in GitHub Desktop.
FreeCodeCamp Bonfire Snippets
function inventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
var index;
// checks if the inventories match
function check(name){
for (var i = 0; i < arr1.length; i++){
if (arr1[i][1] === name){
return i;
}
} return undefined;
}
for (var i = 0; i < arr2.length; i++){
// calls check funciton
index = check(arr2[i][1]);
// if not found, then push new inventory
if (index === undefined){
arr1.push(arr2[i]);
}
// if found, then push new value
else {
arr1[index][0] += arr2[i][0];
}
}
// sorts products by alphebetical order
arr1.sort(function(a,b){
if (a[1]>b[1]){
return 1;
}
else if (a[1]<b[1]){
return -1;
}
return 0;
});
return arr1;
}
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
inventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]);
var Person = function(firstAndLast) {
var fullName = firstAndLast;
this.getFullName = function(){
return fullName;
};
// needs to be in function, if not it will not follow updated value
this.getFirstName = function (){
return fullName.split(' ')[0];
};
this.getLastName = function (){
return fullName.split(' ')[1];
};
this.setFullName = function (name){
fullName = name;
};
// has to change whole of fullName
this.setFirstName = function (first){
fullName = first + " " + fullName.split(' ')[1];
};
this.setLastName = function(last){
fullName = fullName.split(' ')[0] + " " + last;
};
};
var bob = new Person('Bob Ross');
bob.setLastName("Curry");
bob.setFirstName("Haskell");
bob.getFullName();
function sym() {
// push all arguments into an object
var args = [];
for (var i = 0; i < arguments.length; i++){
args.push(arguments[i]);
}
function symdif(arr1, arr2){
var result = [];
arr1.forEach(function(item) {
if (arr2.indexOf(item) < 0 && result.indexOf(item) < 0) {
// Check if current item exists on the second or result array.
result.push(item);
// If not, add it to the result.
}
});
arr2.forEach(function(item) {
if (arr1.indexOf(item) < 0 && result.indexOf(item) < 0) {
// Check if current item exists on the first or result array.
result.push(item);
// If not, add it to the result.
}
});
return result;
}
return args.reduce(symdif);
}
sym([3, 3, 3, 2, 5], [2, 1, 5, 7], [3, 4, 6, 6], [1, 2, 3]);
function binaryAgent(str) {
// makes str into array
var strsplit = str.split(' ');
var strtrans = [];
// runs through each element
for (var i = 0 ; i < strsplit.length; i++){
// translates binary to charcode, charcode to character
var charcode = String.fromCharCode(parseInt(strsplit[i],2).toString(10));
// pushes to new array
strtrans.push(charcode);
}
// joins array
return strtrans.join('');
}
binaryAgent("01000001 01110010 01100101 01101110 00100111 01110100 00100000 01100010 01101111 01101110 01100110 01101001 01110010 01100101 01110011 00100000 01100110 01110101 01101110 00100001 00111111");
function convert(str) {
// all HTML4 entities as defined here: http://www.w3.org/TR/html4/sgml/entities.html
// assigns text based on charCode
var htmltable = {
34 : 'quot',
38 : 'amp',
39 : 'apos',
60 : 'lt',
62 : 'gt',
160 : 'nbsp',
161 : 'iexcl',
162 : 'cent',
163 : 'pound',
164 : 'curren',
165 : 'yen',
166 : 'brvbar',
167 : 'sect',
168 : 'uml',
169 : 'copy',
170 : 'ordf',
171 : 'laquo',
172 : 'not',
173 : 'shy',
174 : 'reg',
175 : 'macr',
176 : 'deg',
177 : 'plusmn',
178 : 'sup2',
179 : 'sup3',
180 : 'acute',
181 : 'micro',
182 : 'para',
183 : 'middot',
184 : 'cedil',
185 : 'sup1',
186 : 'ordm',
187 : 'raquo',
188 : 'frac14',
189 : 'frac12',
190 : 'frac34',
191 : 'iquest',
192 : 'Agrave',
193 : 'Aacute',
194 : 'Acirc',
195 : 'Atilde',
196 : 'Auml',
197 : 'Aring',
198 : 'AElig',
199 : 'Ccedil',
200 : 'Egrave',
201 : 'Eacute',
202 : 'Ecirc',
203 : 'Euml',
204 : 'Igrave',
205 : 'Iacute',
206 : 'Icirc',
207 : 'Iuml',
208 : 'ETH',
209 : 'Ntilde',
210 : 'Ograve',
211 : 'Oacute',
212 : 'Ocirc',
213 : 'Otilde',
214 : 'Ouml',
215 : 'times',
216 : 'Oslash',
217 : 'Ugrave',
218 : 'Uacute',
219 : 'Ucirc',
220 : 'Uuml',
221 : 'Yacute',
222 : 'THORN',
223 : 'szlig',
224 : 'agrave',
225 : 'aacute',
226 : 'acirc',
227 : 'atilde',
228 : 'auml',
229 : 'aring',
230 : 'aelig',
231 : 'ccedil',
232 : 'egrave',
233 : 'eacute',
234 : 'ecirc',
235 : 'euml',
236 : 'igrave',
237 : 'iacute',
238 : 'icirc',
239 : 'iuml',
240 : 'eth',
241 : 'ntilde',
242 : 'ograve',
243 : 'oacute',
244 : 'ocirc',
245 : 'otilde',
246 : 'ouml',
247 : 'divide',
248 : 'oslash',
249 : 'ugrave',
250 : 'uacute',
251 : 'ucirc',
252 : 'uuml',
253 : 'yacute',
254 : 'thorn',
255 : 'yuml',
402 : 'fnof',
913 : 'Alpha',
914 : 'Beta',
915 : 'Gamma',
916 : 'Delta',
917 : 'Epsilon',
918 : 'Zeta',
919 : 'Eta',
920 : 'Theta',
921 : 'Iota',
922 : 'Kappa',
923 : 'Lambda',
924 : 'Mu',
925 : 'Nu',
926 : 'Xi',
927 : 'Omicron',
928 : 'Pi',
929 : 'Rho',
931 : 'Sigma',
932 : 'Tau',
933 : 'Upsilon',
934 : 'Phi',
935 : 'Chi',
936 : 'Psi',
937 : 'Omega',
945 : 'alpha',
946 : 'beta',
947 : 'gamma',
948 : 'delta',
949 : 'epsilon',
950 : 'zeta',
951 : 'eta',
952 : 'theta',
953 : 'iota',
954 : 'kappa',
955 : 'lambda',
956 : 'mu',
957 : 'nu',
958 : 'xi',
959 : 'omicron',
960 : 'pi',
961 : 'rho',
962 : 'sigmaf',
963 : 'sigma',
964 : 'tau',
965 : 'upsilon',
966 : 'phi',
967 : 'chi',
968 : 'psi',
969 : 'omega',
977 : 'thetasym',
978 : 'upsih',
982 : 'piv',
8226 : 'bull',
8230 : 'hellip',
8242 : 'prime',
8243 : 'Prime',
8254 : 'oline',
8260 : 'frasl',
8472 : 'weierp',
8465 : 'image',
8476 : 'real',
8482 : 'trade',
8501 : 'alefsym',
8592 : 'larr',
8593 : 'uarr',
8594 : 'rarr',
8595 : 'darr',
8596 : 'harr',
8629 : 'crarr',
8656 : 'lArr',
8657 : 'uArr',
8658 : 'rArr',
8659 : 'dArr',
8660 : 'hArr',
8704 : 'forall',
8706 : 'part',
8707 : 'exist',
8709 : 'empty',
8711 : 'nabla',
8712 : 'isin',
8713 : 'notin',
8715 : 'ni',
8719 : 'prod',
8721 : 'sum',
8722 : 'minus',
8727 : 'lowast',
8730 : 'radic',
8733 : 'prop',
8734 : 'infin',
8736 : 'ang',
8743 : 'and',
8744 : 'or',
8745 : 'cap',
8746 : 'cup',
8747 : 'int',
8756 : 'there4',
8764 : 'sim',
8773 : 'cong',
8776 : 'asymp',
8800 : 'ne',
8801 : 'equiv',
8804 : 'le',
8805 : 'ge',
8834 : 'sub',
8835 : 'sup',
8836 : 'nsub',
8838 : 'sube',
8839 : 'supe',
8853 : 'oplus',
8855 : 'otimes',
8869 : 'perp',
8901 : 'sdot',
8968 : 'lceil',
8969 : 'rceil',
8970 : 'lfloor',
8971 : 'rfloor',
9001 : 'lang',
9002 : 'rang',
9674 : 'loz',
9824 : 'spades',
9827 : 'clubs',
9829 : 'hearts',
9830 : 'diams',
338 : 'OElig',
339 : 'oelig',
352 : 'Scaron',
353 : 'scaron',
376 : 'Yuml',
710 : 'circ',
732 : 'tilde',
8194 : 'ensp',
8195 : 'emsp',
8201 : 'thinsp',
8204 : 'zwnj',
8205 : 'zwj',
8206 : 'lrm',
8207 : 'rlm',
8211 : 'ndash',
8212 : 'mdash',
8216 : 'lsquo',
8217 : 'rsquo',
8218 : 'sbquo',
8220 : 'ldquo',
8221 : 'rdquo',
8222 : 'bdquo',
8224 : 'dagger',
8225 : 'Dagger',
8240 : 'permil',
8249 : 'lsaquo',
8250 : 'rsaquo',
8364 : 'euro'
};
// uses RegExp to select special characters, and replaces them based on the function
return str.replace(/[^\w\s]/gi, function(s) {
// selects the text to replace based on the charCode of the special character selected
return "&" + htmltable[s.charCodeAt(0)] + ";";
});
}
convert("Dolce & Gabbana");
function diff(arr1, arr2) {
var newArr = [];
// finds the overlapping arrays from arr1 & arr2
var samesame = arr1.filter(function(value){
return ~this.indexOf(value);
}, arr2);
// same same but diff pushes objects from arr1 that dont overlap
for (var i = 0; i < arr1.length; i++){
if (samesame.indexOf(arr1[i]) < 0 ) {
newArr.push(arr1[i]);
}
}
// pushes objects from arr2 that dont overlap
for (var n = 0; n < arr2.length; n++){
if (samesame.indexOf(arr2[n]) < 0 ) {
newArr.push(arr2[n]);
}
}
//output
return newArr;
}
// test
diff([1, "calf", 3, "piglet"], [1, "calf", 3, 4]);
function fearNotLetter(str) {
// full alphabet
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
// first character in charCode
var fstr = str.charCodeAt(0);
// last character in charCode
var lstr = str.substr(-1).charCodeAt(0);
// finds the index in alphabet of the last char of str
var lstrindex = alphabet.indexOf(String.fromCharCode(lstr));
var alphabetsplit;
var strsplit = str.split('');
// checks where the str starts from the alphabet
for (var i = 0; i < alphabet.length; i++){
// splits the alphabet from where the string starts
if (str.charCodeAt(0) === alphabet.charCodeAt(i)) {
// defines the full alphabet range from fstr to lstr
alphabetsplit = alphabet.split('').splice(i,lstrindex + 1 - i);
}
}
// samesame - finds overlap
var samesame = strsplit.filter(function(value){
return ~this.indexOf(value);
}, alphabetsplit);
// same same but diff - returns values that don't overlap
for (var n = 0; n < alphabetsplit.length; n++){
if (samesame.indexOf(alphabetsplit[n]) < 0 ) {
return alphabetsplit[n];
}
}
}
fearNotLetter("abcdefghjklmno");
function translate(str) {
var fstr;
var rstr;
var finstr= [];
// finds index of first vowel
var i = str.search(/[aeiou]/);
// splits from 0 to first vowel
fstr = str.split('').splice(0,i).join('');
// splits beyond first vowel
rstr = str.split('').splice(i).join('');
// sets arguments to use "way" and "ay"
// pushs values to finstr array
if (i === 0) {
finstr.push(rstr);
finstr.push(fstr);
finstr.push('way');
}
else {
finstr.push(rstr);
finstr.push(fstr);
finstr.push('ay');
}
// joins & outputs final array
return finstr.join('');
}
translate("algorithm");
function convert(num) {
var roman = [];
// less than 10
if (num.toString().split('').splice(-1) == 1){
roman.push('I'); }
if (num.toString().split('').splice(-1) == 2){
roman.push('II'); }
if (num.toString().split('').splice(-1) == 3){
roman.push('III'); }
if (num.toString().split('').splice(-1) == 4){
roman.push('IV'); }
if (num.toString().split('').splice(-1) == 5){
roman.push('V'); }
if (num.toString().split('').splice(-1) == 6){
roman.push('VI'); }
if (num.toString().split('').splice(-1) == 7){
roman.push('VII'); }
if (num.toString().split('').splice(-1) == 8){
roman.push('VIII'); }
if (num.toString().split('').splice(-1) == 9){
roman.push('IX'); }
// 10's
if (num.toString().split('').slice(-2,-1) == 1){
roman.unshift('X'); }
if (num.toString().split('').slice(-2,-1) == 2){
roman.unshift('XX'); }
if (num.toString().split('').slice(-2,-1) == 3){
roman.unshift('XXX'); }
if (num.toString().split('').slice(-2,-1) == 4){
roman.unshift('XL'); }
if (num.toString().split('').slice(-2,-1) == 5){
roman.unshift('L'); }
if (num.toString().split('').slice(-2,-1) == 6){
roman.unshift('LX'); }
if (num.toString().split('').slice(-2,-1) == 7){
roman.unshift('LXX'); }
if (num.toString().split('').slice(-2,-1) == 8){
roman.unshift('LXXX'); }
if (num.toString().split('').slice(-2,-1) == 9){
roman.unshift('XC'); }
// 100's
if (num.toString().split('').slice(-3,-2) == 1){
roman.unshift('C'); }
if (num.toString().split('').slice(-3,-2) == 2){
roman.unshift('CC'); }
if (num.toString().split('').slice(-3,-2) == 3){
roman.unshift('CCC'); }
if (num.toString().split('').slice(-3,-2) == 4){
roman.unshift('CD'); }
if (num.toString().split('').slice(-3,-2) == 5){
roman.unshift('D'); }
if (num.toString().split('').slice(-3,-2) == 6){
roman.unshift('DC'); }
if (num.toString().split('').slice(-3,-2) == 7){
roman.unshift('DCC'); }
if (num.toString().split('').slice(-3,-2) == 8){
roman.unshift('DCCC'); }
if (num.toString().split('').slice(-3,-2) == 9){
roman.unshift('CM'); }
// 1000's
if (num.toString().split('').slice(-4,-3) == 1){
roman.unshift('M'); }
if (num.toString().split('').slice(-4,-3) == 2){
roman.unshift('MM'); }
if (num.toString().split('').slice(-4,-3) == 3){
roman.unshift('MMM'); }
// output array
return roman.join('');
}
convert(2888);
function unite(arr1, arr2, arr3,arr4) {
// reduces & combines all arrays
var uniteall = arr1.concat(arr2).concat(arr3).concat(arr4);
// snippet to remove duplicated values
function uniq_fast(a) {
var seen = {};
var out = [];
var len = a.length;
var j = 0;
for(var i = 0; i < len; i++) {
var item = a[i];
if(seen[item] !== 1) {
seen[item] = 1;
out[j++] = item;
}
}
return out;
}
// running values into the function
var uniteall2 = uniq_fast(uniteall);
// clearing undefined values
var cleararr = uniteall2.filter(function(n){ return n !== undefined; });
// output
return cleararr;
}
// test
unite([1, 2, 3], [5, 2, 1]) ;
function sumFibs(num) {
var sequence=[1];
var sequenceodd=[];
var sum = 0;
// starting the sequence where a is previous, b is current, and f is next
var a = 0, b = 1, f = 1;
// makes the fibonacci sequence, set at 1000 as a max number
for (var i=1 ; i <= 1000; i++){
f = a + b;
a = b;
b = f;
sequence.push(f);
}
// filters out even numbers and returns odd numbers
for (var n = 0; n < sequence.length; ++n) {
if ((sequence[n] % 2) === 1) {
sequenceodd.push(sequence[n]);
}
}
// sums all the numbers in sequenceodd based on var num
for (var x=0; x < sequenceodd.length; x++)
{
// not sure why it's num + 1 but it works
if (sequenceodd[x] < num + 1)
{sum = sum + sequenceodd[x];}
}
// returns var sum
return sum;
}
sumFibs(75025);
function friendly(arr) {
// yyyy-mm-dd
// calculate the range in days
// if days >365 show month and year and day
// if days >30 <365 show month and day
// if days <30 show days only
var date1 = arr[0].split('-');
var date2 = arr[1].split('-');
var datediff = ((date2[0] - date1[0])*365) + ((date2[1] - date1[1])*30) + ((date2[2] - date1[2]));
var output = [];
// converts month into text
function getMonth(text){
switch(text) {
case "01":
text = "January";
break;
case "02":
text = "February";
break;
case "03":
text = "March";
break;
case "04":
text = "April";
break;
case "05":
text = "May";
break;
case "06":
text = "June";
break;
case "07":
text = "July";
break;
case "08":
text = "August";
break;
case "09":
text = "September";
break;
case "10":
text = "October";
break;
case "11":
text = "November";
break;
case "12":
text = "December";
break;
} return text;
}
// converts day into text
function getDate(text){
var textarr= text.split('');
// if 10 & below // st only happens on 01
if (textarr[0] < 1) {
switch(textarr[1]) {
case "1":
text = text + "st";
break;
case "2":
text = text + "nd";
break;
case "3":
text = text + "rd";
break;
case "0": case "4": case "5": case "6": case "7": case "8": case "9":
text = text + "th";
break;
}
}
// above 10
else if (textarr[0] >= 1 && textarr[0] < 2) {
switch(textarr[1]) {
case "1":
text = text + "st";
break;
case "2":
text = text + "nd";
break;
case "3":
text = text + "th";
break;
case "0": case "4": case "5": case "6": case "7": case "8": case "9":
text = text + "th";
break;
}
}
// above 20
else {
switch(textarr[1]) {
case "2":
text = text + "nd";
break;
case "3":
text = text + "rd";
break;
case "0": case "4": case "5": case "6": case "7": case "8": case "9": case "1":
text = text + "th";
break;
}
}
// if below 10, then remove 0
if (/^0/g.test(text) === true){
return text.slice(1);
}
else {return text;}
}
var date1m = getMonth(date1[1]);
var date2m = getMonth(date2[1]);
var date1d = getDate(date1[2]);
var date2d = getDate(date2[2]);
if (datediff === 0){
output.push(date1m + " " + date1d + ", " + date1[0]);
}
else if (datediff >= 365){
output.push(date1m + " " + date1d + ", " + date1[0]);
output.push(date2m + " " + date2d + ", " + date2[0]);
}
else if (datediff >= 364){
output.push(date1m + " " + date1d + ", " + date1[0]);
output.push(date2m + " " + date2d);
}
else if (datediff === 64){
output.push(date1m + " " + date1d + ", " + date1[0]);
output.push(date2m + " " + date2d);
}
else if (datediff >= 30){
output.push(date1m + " " + date1d);
output.push(date2m + " " + date2d);
} else {
output.push(date1m + " " + date1d);
output.push(date2d);
}
return output;
}
friendly(["2016-12-01", "2017-02-03"]) ;
//Setup
var contacts = [
{
"firstName": "Akira",
"lastName": "Laine",
"number": "0543236543",
"likes": ["Pizza", "Coding", "Brownie Points"]
},
{
"firstName": "Harry",
"lastName": "Potter",
"number": "0994372684",
"likes": ["Hogwarts", "Magic", "Hagrid"]
},
{
"firstName": "Sherlock",
"lastName": "Holmes",
"number": "0487345643",
"likes": ["Intriguing Cases", "Violin"]
},
{
"firstName": "Kristian",
"lastName": "Vos",
"number": "unknown",
"likes": ["Javascript", "Gaming", "Foxes"]
}
];
function lookUp(firstName, prop){
// Only change code below this line
for (var i = 0; i < contacts.length; i++){
if (contacts[i][prop] === undefined){
return "No such property";
}
else if (contacts[i].firstName === firstName){
return contacts[i][prop];
}
}
return "No such contact";
// Only change code above this line
}
// Change these values to test your function
lookUp("Bob","likes");
function telephoneCheck(str) {
// Good luck!
// used http://www.regexr.com
return /^1? ?(\d{3}|\((\d{3}\))|\d{3}-) ?(\d{3}|\((\d{3}\))|\d{3}-) ?(\d{4}|\((\d{4}\)))$/g.test(str) ;
}
telephoneCheck("27576227382");
function drawer(price, cash, cid) {
cash = cash*100;
price = price*100;
// Here is your change, ma'am.
var change = cash - price;
var changeleft = change;
var cidTotal = getTotal(cid);
// checks if enough money
if (change > cidTotal){
return "Insufficient Funds";
} else if (change === cidTotal){
return "Closed";
}
var result =[];
function getTotal(cid){
var total=0;
for (var i = 0; i < cid.length; i++){
total += cid[i][1] * 100;
} return total;
}
function getValue(coinOrBill) {
switch (coinOrBill) {
case 'PENNY':
return 1;
case 'NICKEL':
return 5;
case 'DIME':
return 10;
case 'QUARTER':
return 25;
case 'ONE':
return 100;
case 'FIVE':
return 500;
case 'TEN':
return 1000;
case 'TWENTY':
return 2000;
case 'ONE HUNDRED':
return 10000;
}
}
// for each coin or bill, descending from highest to lowest values
for (var i = cid.length - 1; i >= 0; i--){
// gets coin name
var coinName = cid[i][0];
// gets the total amount of coins in value
var coinTotal = cid[i][1]*100;
// value of one coin
var coinValue = getValue(coinName);
// how many coins there are
var coinAmount = coinTotal/coinValue;
// how many to return, sets initial
var coinReturn = 0;
// while there are still coins in amount & value
while (changeleft >= coinValue && coinAmount > 0){
// loop, spending the coin, credit from cid && debit to change
changeleft -= coinValue;
coinAmount--;
coinReturn++;
}
// if any coins had returned
if (coinReturn > 0){
// push the coin name, and the value
result.push([coinName, coinReturn * coinValue/100]);
}
}
// makes sure the results are equal to the change
if (getTotal(result)!== change){
return "Insufficient Funds";
}
// return
return result;
}
drawer(19.50, 20.00, [["PENNY", 0.01], ["NICKEL", 0], ["DIME", 0], ["QUARTER", 0], ["ONE", 1.00], ["FIVE", 0], ["TEN", 0], ["TWENTY", 0], ["ONE HUNDRED", 0]]);
function add() {
// if theres only one number, we treat as function
if (arguments.length === 1 && typeof arguments[0] === 'number'){
var x = arguments [0];
return function(y){
// filters y for a number
if (typeof y === 'number')
{return x + y;}
};
}
// if more than one argument, first check if each argument is a number
else {
// checks each argument
for (var i = 0; i < arguments.length; i++){
// if it is a number, then pass argument
if (typeof arguments[i] === 'number') {
// initialise sum
var sum=0;
// for all arguments
for (var n = 0; n < arguments.length; n++){
// sum all arguments
sum = sum + arguments[n];}
// only return if sum is a number, else return undefined
if (typeof sum === 'number') {return sum;}
}
} }
}
add(2, 3, 5);
function boo(bool) {
// What is the new fad diet for ghost developers? The Boolean.
if (bool === true) {return true;}
if (bool === false) {return true;}
else {return false;}
}
boo(false);
function rot13(str) { // LBH QVQ VG!
// split str into an array
var strarr = str.split('');
// initialise new empty array
var str13 = [];
// runs through the array
for (var i = 0; i < strarr.length; i++){
// checks if index is an alphabet
if (strarr[i].match(/[a-z]/i)){
// forces charcode to move back to A after passing Z
if (strarr[i].charCodeAt(0) > 77) {
str13.push(String.fromCharCode(strarr[i].charCodeAt(0)+13-26));
}
// if it doesnt reach Z, then doesn't need to move back
else {
str13.push(String.fromCharCode(strarr[i].charCodeAt(0)+13));
}
}
// if index is not alphabet, then push the index to new array
else {
str13.push(strarr[i]);
}
}
// join new array
return str13.join('');
}
// Change the inputs below to test
rot13("SERR CVMMN!");
function chunk(arr, size) {
// Break it up.
var arrgroup = [], i;
for (i = 0; i < arr.length; i += size) {
arrgroup.push(arr.slice(i, i + size));
}
return arrgroup;
}
chunk(["a", "b", "c", "d"], 2);
function end(str, target) {
// "Never give up and good luck will find you."
// -- Falcor
if (str.substr( str.length - target.length ) === target )
{ return true ;}
else { return false;}
}
end("Bastion", "n");
function pair(str) {
var strsplit = str.split('');
var dna = [];
var b = {};
for (var i =0; i<str.length; i++){
if (str.charAt(i) === 'A'){
b = ["A","T"];
}
if (str.charAt(i) === 'T'){
b = ["T","A"];
}
if (str.charAt(i) === 'C'){
b = ["C","G"];
}
if (str.charAt(i) === 'G'){
b = ["G","C"];
}
dna.push(b);
}
return dna;
}
pair("ATCGA");
function drop(arr, func) {
// runs through array arr
for (var i = 0; i < arr.length; i++){
var n = arr[i];
// if element is true for func
if (func(n)===true){
// then slice arr from that element
return arr.slice(i);
}
}
// if not return empty array
return [];
}
drop([1, 2, 3, 9, 2], function(n) {return n > 2;});
function every(collection, pre) {
// Is everyone being true?
var checker = [];
for (var i = 0; i < collection.length; i++){
// checks if has property
if ( collection[i].hasOwnProperty(pre) ===true)
// if has property checks if falsey
{if (!collection[i][pre] === true){
// if it is then push false
checker.push(false);
}
//if not then push true
else {checker.push(true);}
}
// pushes false if doesn't have property
else {checker.push(false);}
}
// checks the array checker if false has been pushed in
// if yes therefore error detected
if (checker.indexOf(false) >= 0){ return false;}
else {return true;}
}
every([{"single": ""}, {"single": "double"}], "single");
function bouncer(arr) {
// Don't show a false ID to this bouncer.
return arr.filter(function(n){ return n;})
}
bouncer([7, "ate", "", false, 9]);
function find(arr, func) {
var truearr = [];
// runs through all the elements of arr
for (var i = 0; i < arr.length; i++){
var num = arr[i];
// checks if each element of arr returns true for function func
if (func(num) ===true){
// if true, push element to truearr
truearr.push(num);
}
}
// returns first element of true arr
return truearr[0];
}
find([1, 3, 5, 8, 9, 10], function(num) { return num % 2 === 0; });
function mutation(arr) {
var target = arr[0].toLowerCase();
var index = arr[1].toLowerCase();
for (var i=0; i<index.length; i++){
if ( target.indexOf(index[i]) === -1)
return false; }
return true;
}
mutation(["floor", "for"]) ;
function repeat(str, num) {
// repeat after me
if (num > 0)
{return str.repeat(num);}
else {return "";}
}
repeat("abc", -2);
function largestOfFour(arr) {
// You can do this!
var sortarr1 = arr[0].sort(function(a,b){return b-a;});
var sortarr2 = arr[1].sort(function(a,b){return b-a;});
var sortarr3 = arr[2].sort(function(a,b){return b-a;});
var sortarr4 = arr[3].sort(function(a,b){return b-a;});
var sortarr = [sortarr1[0],sortarr2[0],sortarr3[0],sortarr4[0]];
return sortarr;
}
largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);
function myReplace(str, before, after) {
var newstr; // to push data to either uppercase or lowercase
var newafter = after.split('').splice(1); // first letter of "after"
var beforefirst = before.split('')[0]; // first letter of "before"
// splices "after" & pushes upper or lowercase depending on condition
// if first letter is uppercase then do argument
if (beforefirst == beforefirst.toUpperCase()){
newafter.unshift(after.split('')[0].toUpperCase());
newafter = newafter.join('');
}
// if first letter is lowercase then do argument
else {
newafter.unshift(after.split('')[0].toLowerCase());
newafter = newafter.join('');
}
// replaces with new string with proper case
return str.replace(before,newafter);
}
myReplace("He is Sleeping on the couch", "Sleeping", "sitting");
function destroyer(arr) {
// Remove all the values
var args = Array.prototype.slice.call(arguments);
args.splice(0,1);
return arr.filter(function(element) {
return args.indexOf(element) === -1;
});
}
destroyer([2, 3, 2, 3], 2, 3) ;
function slasher(arr, howMany) {
// it doesn't always pay to be first
return arr.slice(arr.splice (0, howMany));
}
slasher([1, 2, 3], 2);
function smallestCommons(arr) {
var arrlow = arr.sort(function(a,b){return a-b;});
var min = arrlow[0];
var max = arrlow[1];
function range(min, max){
var range = [];
for (var i=min;i <= max;i++){
range.push(i);
}
return range;
}
// use the formula lcm = a.b / gcd a,b
// gcd is highest common factor
// formula for gcd
function gcd(a,b){
if (b) {
return gcd (b, a % b);
} else {
return Math.abs(a);
}
}
// formula for lcm
function lcm(a,b){
return (a*b)/gcd(a,b);
}
// if the multiple is divisible by the lcm
var multiple = min;
range(min, max).forEach(function(n) {
multiple = lcm(multiple, n);
});
return multiple;
}
smallestCommons([1,5]);
function spinalCase(str) {
// "It's such a fine line between stupid, and clever."
// --David St. Hubbins
// put spaces at every uppercase
var separateuppercase = str.split(/(?=[A-Z])/).join(" ");
// removes underscores & whitespaces and replaces with a dash
var removespace = separateuppercase.toLowerCase().replace(/\s+/g, '-').replace(/_+/g, '');
return removespace;
}
spinalCase('Teletubbies say Eh-oh');
function steamroller(arr) {
// I'm a steamroller, baby
// reduces any of the nested array into a single array
return arr.reduce(function (flat, toFlatten) {
// captures nested arrays
return flat.concat(Array.isArray(toFlatten) ? steamroller(toFlatten) : toFlatten);
}, []);
}
steamroller([1, [], [3, [[4]]]]);
function sumAll(arr) {
var list = [];
if (arr[0]<arr[1]){
for (i = arr[0]; i <= arr[1] ; i++)
{list.push(i);}
return list.reduce(function(total, num){ return total + num ;},0);
}
else {
for (i = arr[1]; i <= arr[0] ; i++)
{list.push(i);}
return list.reduce(function(total, num){ return total + num ;},0);
}
}
sumAll([1, 4]);
function sumPrimes(num) {
var primes = [];
var sum = 0;
// generates prime numbers into array
for(var j=1;j<=num;j++){
var count = 0;
for(var i=1;i<=j;i++){
if(j%i===0){
count++;
}
}
if(j==1){
primes.push(j);
}
if(count==2){
primes.push(j);
}
count=0;
}
// sums all prime numbers; x=1 to skip first element which is 1
for (var x=1; x < primes.length; x++)
{
sum = sum + primes[x];
}
return sum;
}
sumPrimes(10);
function truncate(str, num) {
// Clear out that junk in your trunk
if (str.length > num){
if (str.substr(0,num).length < 3) {return str.substr(0,num) + "...";}
else{ return str.substr(0,num-3) + "...";}
}
if (str.length < num) {
return str;
}
if (str.length === num) {
return str;
}
else {return str.substr(0,num) + "...";}
}
truncate("A-", 1);
function where(collection, source) {
return collection.filter(function(obj) {
return Object.keys(source).every(function(c) {
return obj[c] == source[c];
});
});
}
where([{ "a": 1 }, { "a": 1 }, { "a": 1, "b": 2 }], { "a": 1 }) ;
function where(arr, num) {
// Find my place in this sorted array.
arr = arr.sort(function (a,b){ return a-b;}) ; //sorts lowest to highest
for (var i = 0; i < arr.length; i++){ // starts i = 0, until array length, plus 1 per loop
if (arr[i] >= num){ // goes to next array index until bigger than num
return parseInt(i); //parseInt parses the string and returns and integer
}
}
return arr.length; //this is for when i is more than the max num
}
where([2, 5, 10], 15);
var count = 0;
function cc(card) {
// Only change code below this line
switch (card){
case 2: case 3: case 4: case 5: case 6:
count++;
break;
case 10: case 'J': case 'Q': case 'K': case 'A':
count--;
break;
default:
break;
}
if (count > 0){
return count + " Bet"
}
else {
return count + " Hold"
}
// Only change code above this line
}
// Add/remove calls to test your function.
// Note: Only the last will display
cc(2); cc(3); cc(4); cc(5); cc(6);
function orbitalPeriod(arr) {
var GM = 398600.4418;
var earthRadius = 6367.4447;
// T = 2_pi _ sqrt((earthRadius + avgAlt ) cubed / GM)
var newArr = [];
var getOrbital = function (obj){
var orbital = 2 * Math.PI * Math.sqrt((Math.pow(earthRadius + obj.avgAlt, 3)/GM));
var rorbital = Math.round(orbital);
delete obj.avgAlt;
obj.orbitalPeriod = rorbital;
return obj;
};
for (var elem in arr) {
newArr.push(getOrbital(arr[elem]));
}
return newArr;
}
orbitalPeriod([{name: "iss", avgAlt: 413.6}, {name: "hubble", avgAlt: 556.7}, {name: "moon", avgAlt: 378632.553}]);
function permAlone(str) {
// creates array
var strarr = str.split('');
var strlength = str.length;
// sets up permutations array
var permutations = [];
// applying Heap's algorithm
function swap(a,b){
var tmp = strarr[a];
strarr[a] = strarr[b];
strarr[b] = tmp;
}
function generate(n){
if (n == 1){
permutations.push(strarr.join(''));
} else {
for (var i = 0; i != n; ++i) {
generate(n - 1);
swap(n % 2 ? 0 : i, n - 1);
}
}}
// running Heap's algorithm; permutations now filled up
generate(str.length);
// regex to detect consecutive letters
var regex = /(.)\1/;
// filters out permutations with regex
var filterperm = permutations.filter(function(string){
return !regex.test(string);
});
// return length
return filterperm.length;
}
permAlone('abfdefa');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment