Week 01 → Day 002 → Tues → August 8, 2017
Index
Coding Challenge ⋰ longestString
Review ⋰ Q&A with Karthik ⋰ ES6 Object property shorthand ⋰ Anonymous & Callback Functions ⋰ .map()
⋰ Iterating Over Arrays, Array of Objects
Pair Programming with Adam Lower ⋰ Advanced JavaScript ⋰ es6.js
⋰ arrays.js
Brown Bag with Ryan Hamblin ⋰ Slack Overview
Review ⋰ Q&A with Karthik ⋰ How to Solve a Problem ⋰ Basic-JS Review ⋰ Advanced-JS/arrays.js Overview ⋰ .reduce()
Coding Challenge ⋰ longestString
/* 0. Instructions
* Write a function that accepts an array of strings.
* Return the longest string in the array.
*/
/* 1. Identify Test Cases
const a = ['abc', 'a', 'b'] // -> 'abc'
const b = ['abc', 'def'] // -> 'def'
const c = [] // -> null
const d = ['asdfasfas', 'sdfadfsa', 'asfasfasdfasfasfd', 's'] // -> 'asfasfasdfasfasfd'
*/
/* 2. Pseudo-Code
function longestString strings
loop over the array of strings
do something in the loop
return longestString
*/
/* 3a. Solution #1
const longestStr = (arr) => {
let x = '';
for (let i = 0; i < arr.length; i++) {
if (arr[i].length > x.length) x = arr[i];
}
return x;
};
*/
// 3b. Solution #2
const longestStr = (arr) => {
let x = arr[0];
arr.forEach(i => {
if (i.length > x.length) x = i;
});
return x;
}
Review ⋰ Q&A ━ Karthik Viswanathan
ES6 Object property shorthand ━ 🗣 0:42
const name = 'Karthik'
const person = {
name: name // the old way of writing Object property
} // the key and value share the same name
const person = {
name // the new way. key is String 'name'
} // value is the value of 'name' variable
Anonymous ⋰ Callback functions ⋰ .map()
━ 🗣 3:58
Anonymous functions don't have an assigned name:
(x) => x + 4
They're often used as parameters or as callback functions. In the example below, we're passing an anonymous function into .map()
. The anonymous function, which is also a callback function, is taking each element of the array and adding 4 to it and then returning a new array with the new values.
[1, 2, 3].map((x) => x + 4) // [5, 6, 7]
Common use case with _callback functions _is on a website, when a button is clicked, an event is triggered and then a _callback function _is called.
runButton.onClick(() => {
// Do something when runButton is clicked
})
Callback function exercise ⋰ Finding the largest element in an Array ━ 🗣 13:18
// Pseudo-code
// 0. set maximum = array[0]
// 1. loop over the array
// 2. see if the current element is greater than any element we've previously seen
// 3. if 2, then that's the new maximum
// after the loop, 4. return the maximum
const max = (array) => {
let maximum = array[0];
for (let i = 0; i < array.length; i++) {
if (array[i] > maximum) {
maximum = array[i];
}
}
return maximum;
};
max([1, 2, 3]); // 3
Finding the largest element in an Array of Objects ━ 🗣 21:15
const max = (array, cb) => {
let maximumValue = cb(array[0]);
let maximumElement = array[0];
for (let i = 0; i < array.length; i++) {
if (cb(array[i]) > maximumValue) {
maximumValue = cb(array[i]);
maximumElement = array[i];
}
}
return maximumElement;
};
const people = [{name: "Bob", age: 50}, {name: "Jill", age: 20}];
console.log(max(people, p => p.age)); // {name: "Bob", age: 50}
[Edge case] With no elements in the Array considered ━ 🗣 28:08
const max = (array, cb) => {
if (array.length === 0) {
throw new Error("array must not be empty");
}
let maximumValue = cb(array[0]);
let maximumElement = array[0];
for (let i = 0; i < array.length; i++) {
if (cb(array[i]) > maximumValue) {
maximumValue = cb(array[i]);
maximumElement = array[i];
}
}
return maximumElement;
};
max([], n => n); // error: can't find the max of an empty array
Pair programming with Adam Lower ━ Advanced JavaScript
es6.js ⋰ arrays.js
Brown Bag ━ Slack ━ Ryan Hamblin
Review ⋰ Q&A ━ Karthik Viswanathan
How to solve a problem ⋰ Basic-JavaScript/project-3.js
sumUserPostLikes
Review ━ 🗣 0:00
- Read the
// comments
- Explain it in your own words
- Write/Visualize any data structures (nested Arrays and Objects)
- Write Pseudo-code
- Translate Pseudo-code to actual code
// 1. Read the comments
// user has an array property called 'posts'
// posts is an array of post objects
// each post object has an integer property called 'likes'
// sum together the likes from all the post objects
// return the sum
// 2i. Visualize the data structure
const user = {
posts: [
{ likes: 2 },
{ likes: 5 },
{ likes: 10}
]
}
user.posts = [{likes: 2}, {likes: 5}, {likes: 10}]
user.posts.length = 3
// 3. Write Pseudo-code
// initialize sum = 0
// loops through all posts
// add the current post's like count to the sum
// return sum
// 4. Translate Pseudo-code to actual code
const sumUserPostLikes = (user) => {
let sum = 0;
for (let i = 0; i < user.posts.length; i++) {
sum += user.posts[i].likes;
}
return sum;
};
// Alternate solution using .map() & .reduce()
const sumUserPostLikes = user => user.posts.map(x => x.likes).reduce((a, b) => a + b)
When referring to Objects, value and property are not the same but are sometimes referring to the value of the property. The property of an Object is thekey
: value
pair. ━ 🗣 5:38m
const object = {
name: 'Bob', // ← value is String
age: 50, // ← value is Number
likesFun: false // ← value is Boolean
} // ^ key is String
Advanced-JavaScript/arrays.js
Overview ━ 14:34
Implementing the problem solving technique explained earlier:
// Read the comments
// Iterates over a list of elements, yielding each in turn to the `cb` function.
// This only needs to work with arrays.
// based off http://underscorejs.org/#each
In addition, you should read the relevant code from the test.js
file. In this case, arrays.test.js
. These test files make it clear what the expected behavior of the code is. ━ 🗣 17:25
// arrays.test.js
describe('arrays', () => {
describe('each', () => {
it('should invoke cb on each array element', () => {
let count = 0;
arrayMethods.each([1, 2, 3], (element) => {
count += element;
});
expect(count).toBe(6);
});
// initialize count to 0
// each() will call the callback function
// and pass in each element of the array
// once per element.
// inside the callback function, it will add
// each element to the count.
// count should equal 6.
it('should pass the element and the index to cb', () => {
let count = 0;
arrayMethods.each([1, 2, 3], (element, index) => {
count += element + index;
});
expect(count).toBe(9);
});
// initialize count to 0
// each() will call the callback function
// and pass in two parameters (the element of the array
// and the index of that element in the array).
// inside the callback function, it will add each
// element AND indices to the count.
// count should equal 9.
});
// Solution
const each = (elements, cb) => {
for (let i = 0; i < elements.length; i++) {
cb(elements[i], i);
}
};
How the .reduce()
function works ━ 🗣 22:27
// Read the comments
// Combine all elements into a single value going from left to right.
// Elements will be passed one by one into `cb`.
// `memo` is the starting value. If `memo` is undefined then make `elements[0]` the initial value.
// arrays.test.js
describe('reduce', () => {
.
.
.
it('should accept a memo argument', () => {
const arr = [1, 2, 3, 4, 5];
const result = arrayMethods.reduce(arr, (memo, num) => (memo + num), 10);
expect(result).toBe(25);
});
// initialize arr with [1, 2, 3, 4, 5]
// call reduce() and pass in the array and a callback function.
// the callback function takes in two parameters (memo, num)
// memo is just a value we're incrementally building up by adding num.
// num is the current element in the array.
// memo + num is returned each time the callback function is ran.
// 10 is the initial value of memo.
// the callback function is called for each element in the array.
// memo = 10
// cb(10, 1) => 11
// memo = 11
// cb(11, 2) => 13
// memo 13
// cb(13, 3) => 16
// memo 16
// cb(16, 4) => 20
// memo 20
// cb(20, 5) => 5
// memo 25
// return 25
// Solution
const reduce = (elements, cb, memo = elements.shift()) => {
if (memo === undefined) {
memo = elements[0];
for (let i = 0; i < elements.length; i++) {
memo = cb(memo, elements[i]);
}
} else {
for (let i = 0; i < elements.length; i++) {
memo = cb(memo, elements[i]);
}
return memo;
}
};
Extra Resources ━ 🗣 30:19
MDN web docs - Array.prototype.reduce()