Skip to content

Instantly share code, notes, and snippets.

@ben-rubin
Created July 5, 2020 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ben-rubin/3c92b4eff160f2f67619ab6fab1950a8 to your computer and use it in GitHub Desktop.
Save ben-rubin/3c92b4eff160f2f67619ab6fab1950a8 to your computer and use it in GitHub Desktop.
// Type JavaScript here and click "Run Code" or press Ctrl + s
// Challenge 1
function addTwo(num) {
return num + 2;
}
// To check if you've completed it, uncomment these console.logs!
console.log(addTwo(3));
console.log(addTwo(10));
// Challenge 2
function addS(word) {
return word + 'S';
}
// uncomment these to check your work
console.log(addS('pizza'));
console.log(addS('bagel'));
// Challenge 3
// Without builtin map
function map(array, callback) {
let result = [];
array.forEach(e => result.push(callback(e)));
return result;
}
console.log(map([1, 2, 3], addTwo));
// Challenge 4
let alphabet = '';
const letters = ['a', 'b', 'c', 'd'];
forEach(letters, function (char) {
alphabet += char;
});
function forEach(array, callback) {
array.forEach(e => callback(e));
}
console.log(alphabet); //prints 'abcd'
// see for yourself if your forEach works!
// Challenge 5
function mapWith(array, cb) {
let result = [];
forEach(array, e => result.push(cb(e)));
return result;
}
let myArray = [1, 2, 3, 4];
console.log(myArray)
console.log(mapWith(myArray, addTwo));
// Challenge 6
function reduce(array, callback, initialValue) {
forEach(array, e => initialValue = callback(initialValue, e));
return initialValue;
}
const nums = [4, 1, 3];
const cb = (a, b) => a + b;
console.log(reduce(nums, cb, 0));
// Challenge 7
function intersection(arrays) {
return reduce(
Array.prototype.slice.call(arguments, 1),
(initialValue, array) => initialValue.filter(e => array.indexOf(e) >= 0),
arguments[0]
);
}
console.log(intersection([5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5]));
// should log: [5, 15]
// Challenge 8
function union(arrays) {
let callback = (initialValue, array) => {
for (const e of array) {
if (initialValue.indexOf(e) === -1) {
initialValue.push(e);
}
}
return initialValue;
}
return reduce(
Array.prototype.slice.call(arguments, 1),
callback,
arguments[0]
);
}
console.log(union([5, 10, 15], [15, 88, 1, 5, 7], [100, 15, 10, 1, 5]));
// should log: [5, 10, 15, 88, 1, 7, 100]
// Challenge 9
function objOfMatches(array1, array2, callback) {
let obj = {};
for (let idx = 0; idx < array1.length; idx++) {
let el1 = array1[idx];
let el2 = array2[idx];
if (el2 === callback(el1)) {
obj[el1] = el2;
}
}
return obj;
}
console.log(objOfMatches(['hi', 'howdy', 'bye', 'later', 'hello'], ['HI', 'Howdy', 'BYE', 'LATER', 'hello'], function (str) {
return str.toUpperCase();
}));
// should log: { hi: 'HI', bye: 'BYE', later: 'LATER' }
// Challenge 10
function multiMap(arrVals, callbacks) {
let obj = {};
arrVals.forEach(v => {
obj[v] = callbacks.map(c => c(v))
});
return obj;
}
console.log(multiMap(['catfood', 'glue', 'beer'], [
function (str) {
return str.toUpperCase();
},
function (str) {
return str[0].toUpperCase() + str.slice(1).toLowerCase();
},
function (str) {
return str + str;
}
]));
// should log: { catfood: ['CATFOOD', 'Catfood', 'catfoodcatfood'], glue: ['GLUE', 'Glue', 'glueglue'], beer: ['BEER', 'Beer', 'beerbeer'] }
// Challenge 11
function objectFilter(obj, callback) {
let newObj = {};
Object.keys(obj).forEach(k => {
if (obj[k] === callback(k)) {
newObj[k] = obj[k];
}
});
return newObj;
}
const cities = {
London: 'LONDON',
LA: 'Los Angeles',
Paris: 'PARIS',
};
console.log(objectFilter(cities, city => city.toUpperCase())) // Should log { London: 'LONDON', Paris: 'PARIS'}
// Challenge 12
function majority(array, callback) {
let count = reduce(
array,
(i, e) => callback(e) ? ++i : i,
0
);
return count > array.length / 2;
}
// /*** Uncomment these to check your work! ***/
function isOdd(num) {
return num % 2 === 1;
}
console.log(majority([1, 2, 3, 4, 5], isOdd)); // should log: true
console.log(majority([2, 3, 4, 5], isOdd)); // should log: false
// Challenge 13
function prioritize(array, callback) {
let trues = [];
let falses = [];
array.forEach(e => {
if (callback(e)) {
trues.push(e);
} else {
falses.push(e);
}
});
return trues.concat(falses);
}
// /*** Uncomment these to check your work! ***/
const startsWithS = function (str) {
return str[0] === 's' || str[0] === 'S';
};
console.log(prioritize(['curb', 'rickandmorty', 'seinfeld', 'sunny', 'friends'], startsWithS)); // should log:
//['seinfeld', 'sunny', 'curb', 'rickandmorty', 'friends']
// Challenge 14
function countBy(array, callback) {
let obj = {};
array.forEach(e => {
let val = callback(e);
if (obj.hasOwnProperty(val)) {
obj[val] += 1;
} else {
obj[val] = 1;
}
});
return obj;
}
// /*** Uncomment these to check your work! ***/
console.log(countBy([1, 2, 3, 4, 5], function (num) {
if (num % 2 === 0) return 'even';
else return 'odd';
})); // should log: { odd: 3, even: 2 }
// Challenge 15
function groupBy(array, callback) {
let obj = {};
array.forEach(e => {
let val = callback(e);
if (obj.hasOwnProperty(val)) {
obj[val].push(e);
} else {
obj[val] = [e];
}
})
return obj;
}
// /*** Uncomment these to check your work! ***/
const decimals = [1.3, 2.1, 2.4];
const floored = function (num) {
return Math.floor(num);
};
console.log(groupBy(decimals, floored)); // should log: { 1: [1.3], 2: [2.1, 2.4] }
// Challenge 16
function goodKeys(obj, callback) {
let matches = [];
Object.keys(obj).forEach(k => {
if (callback(obj[k])) {
matches.push(k);
}
});
return matches;
}
// /*** Uncomment these to check your work! ***/
const sunny = {
mac: 'priest',
dennis: 'calculating',
charlie: 'birdlaw',
dee: 'bird',
frank: 'warthog'
};
const startsWithBird = function (str) {
return str.slice(0, 4).toLowerCase() === 'bird';
};
console.log(goodKeys(sunny, startsWithBird)); // should log: ['charlie', 'dee']
// Challenge 17
function commutative(func1, func2, value) {
return func2(func1(value)) === func1(func2(value));
}
// /*** Uncomment these to check your work! ***/
const multBy3 = n => n * 3;
const divBy4 = n => n / 4;
const subtract5 = n => n - 5;
console.log(commutative(multBy3, divBy4, 11)); // should log: true
console.log(commutative(multBy3, subtract5, 10)); // should log: false
console.log(commutative(divBy4, subtract5, 48)); // should log: false
// Challenge 18
function objFilter(obj, callback) {
let newObj = {};
Object.keys(obj).forEach(k => {
if (obj[k] === callback(k)) {
newObj[k] = obj[k];
}
});
return newObj;
}
// /*** Uncomment these to check your work! ***/
const startingObj = {};
startingObj[6] = 3;
startingObj[2] = 1;
startingObj[12] = 4;
const half = n => n / 2;
console.log(objFilter(startingObj, half)); // should log: { 2: 1, 6: 3 }
// Challenge 19
function rating(arrOfFuncs, value) {
let count = 0;
if (arrOfFuncs.length === 0) {
return 0;
}
arrOfFuncs.forEach(f => f(value) ? count++ : null);
return (count / arrOfFuncs.length) * 100;
}
// /*** Uncomment these to check your work! ***/
const isEven = n => n % 2 === 0;
const greaterThanFour = n => n > 4;
const isSquare = n => Math.sqrt(n) % 1 === 0;
const hasSix = n => n.toString().includes('6');
const checks = [isEven, greaterThanFour, isSquare, hasSix];
console.log(rating(checks, 64)); // should log: 100
console.log(rating(checks, 66)); // should log: 75
// Challenge 20
function pipe(arrOfFuncs, value) {
if (arrOfFuncs.length === 0) {
return value;
}
let newValue = arrOfFuncs.shift()(value);
// stopping at zero is easier to read but this is one less loop
if (arrOfFuncs.length === 1) {
return arrOfFuncs[0](newValue);
}
return pipe(arrOfFuncs, newValue);
}
// /*** Uncomment these to check your work! ***/
const capitalize = str => str.toUpperCase();
const addLowerCase = str => str + str.toLowerCase();
const repeat = str => str + str;
const capAddlowRepeat = [capitalize, addLowerCase, repeat];
console.log(pipe(capAddlowRepeat, 'cat')); // should log: 'CATcatCATcat'
// Challenge 21
function highestFunc(objOfFuncs, subject) {
let keys = Object.keys(objOfFuncs);
return keys.slice(1).reduce(
(a, b) => (objOfFuncs[a](subject) > objOfFuncs[b](subject)) ? a : b,
keys[0]
);
}
// /*** Uncomment these to check your work! ***/
const groupOfFuncs = {};
groupOfFuncs.double = n => n * 2;
groupOfFuncs.addTen = n => n + 10;
groupOfFuncs.inverse = n => n * -1;
console.log(highestFunc(groupOfFuncs, 5)); // should log: 'addTen'
console.log(highestFunc(groupOfFuncs, 11)); // should log: 'double'
console.log(highestFunc(groupOfFuncs, -20)); // should log: 'inverse'
// Challenge 22
function combineOperations(startVal, arrOfFuncs) {
return pipe(arrOfFuncs, startVal);
}
function addTen(num) {
return num + 10;
}
function add100(num) {
return num + 100;
}
function divByFive(num) {
return num / 5;
}
function multiplyByThree(num) {
return num * 3;
}
function multiplyByFive(num) {
return num * 5;
}
// /*** Uncomment these to check your work! ***/
console.log(combineOperations(0, [add100, divByFive, multiplyByThree])); // Should output 60 -->
console.log(combineOperations(0, [divByFive, multiplyByFive, addTen])); // Should output 10
// Challenge 23
function myFunc(array, callback) {
}
const numbers = [2, 3, 6, 64, 10, 8, 12];
const evens = [2, 4, 6, 8, 10, 12, 64];
// /*** Uncomment these to check your work! ***/
console.log(myFunc(numbers, isOdd)); // Output should be 1
console.log(myFunc(evens, isOdd)); // Output should be -1
// Challenge 24
function myForEach(array, callback) {
}
let sum = 0;
function addToSum(num) {
sum += num;
}
// /*** Uncomment these to check your work! ***/
// const nums = [1, 2, 3];
// myForEach(nums, addToSum);
// console.log(sum); // Should output 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment