import CheckIcon from '@material-ui/icons/Done';
import CheckAllIcon from '@material-ui/icons/DoneAll';
Figuring Out JavaScript One Mistake at a Time
import CheckIcon from '@material-ui/icons/Done';
import CheckAllIcon from '@material-ui/icons/DoneAll';
Material-UI components use the withStyles higher order component. With this default setup,
(withStyles(styles)(SimpleCard))
you are unable to connect to Redux the traditional way with mapStateToProps like the following example.
Instead, you can use the following syntax. Fyi, addPost is referring to a one of my action creators in this project and SimpleCard is referring to the Cards component from Material-UI.
export default connect(state => { }, { onAddPost: addPost })(withStyles(styles)(SimpleCard));
Below are a few things to keep in mind:
1. With this approach, there is no need for the mapStateToProps function.
2. Actions are accessed via props.actionName (whatever you decided to name your action)
3. Include each action creator in the propTypes i.e. onAddPost: PropTypes.func.isRequired
To enable vertical scrolling on a React component, be sure to give it a height value and an overflowY value of scroll.
Example:
const styles = { height: 256, overflowY: 'scroll' }
If you have merge conflicts in your project, you can quickly find every page with merge conflicts by doing a search in your codebase for >>>.
Material-UI v1 App Bar demo code.
To make a Material-UI Appbar fixed (always visible at the top of the page), you simply need to change the value of the position attribute from “static” to “fixed.”
A fixed App Bar component will cover up the top part of the content beneath it, so be sure to add top padding to whatever content or component is being displayed beneath the App Bar. A top padding of 64 works well.
View the image below to see how I added a top padding of 64 on my List component (I’m using inline styles, but you can use whatever method you prefer).
If you have the json data in a file, you can display the data with only a few steps.
Original Problem via Khan Academy
In this challenge you will write a recursive function that returns the value of n!
.
Start by writing the base case:
if n
is zero, then factorial should just return the value 1.
My Attempt/Solution
I ran into this problem in the past with Free Code Camp’s factorial algorithm problem, but I now have more context of what is happening in the solution based on Khan Academy’s readings.
Below, I’m using the ES6 syntax. First, I’m checking if n is a negative number. If so, return -1. Next, I’m checking if n === 0. If so, return 1 since 0! equals 1. Lastly, if n is a positive number, we want to multiply n by factorial(n – 1). This will multiply n by each descending number until you get to 1. i.e. if n is 5, this will create 5 * 4 * 3 * 2 * 1.
const factorial = (n) => { if (n < 1) { return -1; } else if (n === 0) { return 1; } else { return (n * factorial(n - 1)); } } factorial(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”
function myReplace(str, before, after) { return str; } myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
My Attempt
First as usual, I like to get some things logged to the screen to make sure I’m aware of what I’m working with. I use template strings to write the name of each argument as well as it’s assigned value on the same line without having to use use concatenation.
Then, I jotted some comments of steps I thought I’d need to take to work towards the solution. The question is asking you to replace a certain word in a string with another, specific word, so I thought I’d need to turn the string into an array to be able to loop through it, check for the word to replace, then replace it with the second word.
console.log(`str: ${str}`); console.log(`before: ${before}`); console.log(`after: ${after}`); // split string into an array // search array to see if index === after // if so, splice to remove before and add after //figure out case requirement
At this point, it’s time to start plugging things in. The string was successfully split into an array, and I used .map to loop through the array. Below, I wanted to print true if anything in the array equaled the word that we needed to replace. Then, I’d know if I was on the right track.
const myReplace = (str, before, after) => { // split str into an array const arr = str.split(' '); console.log(arr); // search array to see if index === after const newPhrase = arr.map(word => { if (word === before) { return true; } return false }); // if so, splice to remove before and add after //figure out case requirement return newPhrase; }; myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
After being confused with everything that was returning, I eventually remembered that .splice() mutates the original array opposed creating a new one (I had gotten used to new arrays being created from methods such as .map, .filter, .reduce, etc.) Changing the return back to arr gave the results I was looking for.
Below on arr.splice, I’m using the number 4 to target the specific index that I wanted to remove (since ‘jumped’ is at index 4), 1 is there to remove 1 item, and the string ‘leaped’ is going to replace ‘jumped’. This passes the test case. However, this of coarse will not pass any other test case.
const myReplace = (str, before, after) => { // split str into an array const arr = str.split(' '); console.log(arr); // search array to see if index === after const newPhrase = arr.map(word => { if (word === before) { arr.splice(4, 1, 'leaped'); // newPhrase.replace('jumped', 'leaped'); } }); // if so, splice to remove before and add after //figure out case requirement return arr.join(' '); }; myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
When trying to substitute 4 with before and ‘leaped’ with after (the arguments given), I couldn’t get anything correct to return.
Solution
After reviewing the answer, I see that I was off-track from the beginning. .indexOf is another one of those things that I’ve seen often but haven’t applied enough on a regular basis to have thought of it initially.
The solution has comments, so you should be able to see what they’re doing. If not, feel free to ask me.
function myReplace(str, before, after) { // Find index where before is on string var index = str.indexOf(before); // Check to see if the first letter is uppercase or not if (str[index] === str[index].toUpperCase()) { // Change the after word to be capitalized before we use it. after = after.charAt(0).toUpperCase() + after.slice(1); } // Now replace the original str with the edited one. str = str.replace(before, after); return str; } // test here myReplace("A quick brown fox jumped over the lazy dog", "jumped", "leaped");
Today was yet another humbling trip to the Free Code Camp forums, but an opportunity to learn none-the-less. After all, this is getScript(‘Or Die Tryin’), and I’m not dead yet. On to the next!
Original Problem
You have an array of numbers. Your task is to sort ascending odd numbers and descending even numbers.
Note that zero is even number. If you have an empty array, you need to return it.
Example
sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 8, 4, 5, 2]
// [2, 22, 37, 11, 4, 1, 5, 0] => [22, 4, 1, 5, 2, 11, 37, 0]
// [1, 111, 11, 11, 2, 1, 5, 0] => [1, 1, 5, 11, 2, 11, 111, 0]
My attempt
After looking over the instructions, I wanted to play around with .filter() to pull out sorted even and odd numbers. I like to get a feel of the info I’m working with and to start logging things to the screen as I hopefully work towards the correct solution.
The code below obviously wouldn’t work because .sort() doesn’t sort numbers correctly. .sort() sorts according to string Unicode code points i.e. [1, 2, 10] would sort to [1, 10, 2].
const sorter = (arr) => { // console.log(`arr.sort(): ${arr.sort()}`); console.log(`arr: ${arr}. We want 1, 3, 8, 4, 5, 2`); const evens = arr.filter(x => (x % 2 === 0) ? x : null).sort(); console.log(`evens ${evens}`); const odds = arr.filter(x => (x % 2 !== 0) ? x : null).sort(); console.log(`odds: ${odds}`); }; sorter([5, 3, 2, 8, 1, 4, ]); //[1, 3, 8, 4, 5, 2]
As I continued to think about how to get to the solution, I couldn’t quite understand how to go about the order specifically (i.e. why 8 comes after 3).
Turns out, the positioning of evens and odds was based on their original positions. And you need to you the compareFunction to sort the numbers correctly (something I somehow KEEP forgetting how to do)!
Solution
const sorter = (arr) => { const odds = arr.filter(x => x%2).sort((a,b) => a-b); const evens = arr.filter(x => !(x%2)).sort((a,b) => b-a); console.log(`evens: ${evens}, odds: ${odds}`); return arr.map((cur) => cur % 2 === 0 ? evens.shift() : odds.shift()); }; sorter([5, 3, 2, 8, 1, 4]);
After filtering and sorting correctly, you’ll map through and check if the current number is even or odd, using .shift() to move the current number away from the front of the array appropriately.
The console.log was just me checking to make sure my odds and evens were correct. I used `template literals` and ${expressions} to avoid using the rather annoying JavaScript concatenation syntax.
Original Problem
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 its value, that was passed on as the second argument.
function whatIsInAName(collection, source) { // What's in a name? var arr = []; // Only change code below this line // Only change code above this line return arr; } whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
This is another interesting and tricky intermediate algorithm challenge. While the instructions were clear, I wasn’t sure where to start. I knew I needed to find a way to check to see if the object from the second argument was present anywhere in the first argument.
What I like to do is start writing comments of what I think I should do and/or write out some ES6 array methods to get some things on the screen (to get started and to practice to make sure I’m using them correctly). Below are some of my notes making sure I was using .map and .filter correctly followed by an attempt to compare the arguments with a nested for loop.
const whatIsInAName = (collection, source) => { // What's in a name? let arr = []; // Only change code below this line let name = collection.map(obj => obj.first === "Tybalt" ? obj.last : "Not a match"); console.log(name); let name2 = collection.filter(obj => obj.first === "Tybalt"); console.log(name2); for (let i = 0; i < collection.length; i++) { for (let j = 0; j < source.length; j++) { if (collection[i] === source[i]) { console.log(collection[i]); } } } // Only change code above this line return arr; }; whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
function whatIsInAName(collection, source) { var srcKeys = Object.keys(source); // filter the collection return collection.filter(function (obj) { for(var i = 0; i < srcKeys.length; i++) { if(!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) { return false; } } return true; }); } // test here whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
The basic solution reminded me of a few different object properties that I hadn’t used in awhile and obviously didn’t consider using.
In a nutshell, this solution uses Object.keys to get an array of the key of the second argument, (making srcKeys equal to [ ‘last’]) then filters through collection, using a for loop and an if statement to see if the object in the collection argument doesn’t have the key and the property value doesn’t match the value in the source argument.