TIL document.designMode

Today Nicolas Goutay, a colleague at Orbit showed me how to turn a webpage into design mode. This can help show requested changes to co-workers by editing the page and taking a screen shot, or just to have fun changing pages as you would like.

Head to the console of the webpage you would like to edit, and type document.designMode = "on" and start editing the text on the page!

Have fun!

Run yarn command in a different directory, and starting up 2 servers with node/yarn

If you would like to run a yarn command from another directory you can use –cwd.

yarn --cwd <path> <yarn command>

An example for starting the client from the /client path would be yarn --cwd client start

This is super helpful when trying to start a server and client side app concurrently.

Install the concurrently npm.

And in your scripts file in the package.json add:

  "scripts": {
    "server": "nodemon index.js",
    "client": "yarn --cwd client start",
    "start": "concurrently \"yarn server\" \"yarn client\""
  },

 

Now yarn start will start up both servers in a single terminal with one command!

 

React Dom Rendering on Callback to a Mother Component

I just wanted to share what I learned recently regarding how React only updates the specific render it needs to, and I would have thought otherwise.

My app has a layout like this

App > Posts > Post

App controls all the state and renders Posts, Posts maps through all the this.state.posts and renders each one Post, and Post renders the post details.

I wanted to toggle between that Post view and a PostForm if the user clicked edit. See here a short example:

So I passed a function from Post to App handling edit and changing this.state.edit from false to true.

Now I just need to know where to put my ternary regarding which component to render based on this.state.edit.

So first thing that came to mind was that App would re-render because state within App changed (the this.state.edit now is true, and is located in App), so in my Posts map, I found the post that matched the id of the edit (which I had also added to state), and put my ternary in there.

post.id === updatedPost.id && this.state.edit ? <PostForm …. /> : <Post … />

And I was all excited to see it work, and nothing happened. Nothing changed. Ok, maybe my code was a little wrong, let’s load up our handy debugger and watch each step happen from the handleUpdate callback from Post to App, and go step by step.

I watched the callback head into the App, update the state, so far so good. Now I am ready to see it head into the render of App, and then load up the Posts map, but much to my surprise, the very next step was the Post render. React really held in memory that we are in the Post component, and as soon as we finish our callback, even though it’s in another component, it went straight back to where it was and did not need to update the whole DOM again. Pretty amazing.

So to make this form and Post toggle ended up being simpler than expected, because I didn’t even have to check if post.id === updatedPost.id. React already remembered the scope we were in, and went back only to that one instance of Post component, and updated that into a form.

No wonder React can be so fast, here I had 40 posts on a page, and instead of re-rendering all 40 posts, it knew only to render that small single Post or Form with very little code and logic.

React does not fail to amaze me.

 

In My Own Words: Self Invoking Function JS

I have never seen a self invoking function, and today during my shift as a tech coach at Flatiron School a student asked about it, so I had to do some quick learning. It is rather cool, not quite sure how I would apply it to my code yet, but it is a cool feature to see.

Here is the example from the w3schools closures tutorial (because it uses closure too!):

1
2
3
4
5
var add = (function add () {
    var counter = 0;
    console.log(counter)
    return function () {return counter += 1;}
})();

 

With this block of code every time I call add() it ups the counter.

add();
add();
add();

// the counter is now 3

At a quick glance one would think that every time add() is called it sets var counter = 0 and then the inner function adds 1, and then when you call it again the counter is reset to 0 and again added 1. But it keeps incrementing without resetting to 0.

If you look closer, this function is wrapped in a (), and then immediately invoked with a (). (function{})() Hence the term self invoking function. When this function is loaded initially it creates the variable of counter and assigns it 0.

Then when we call add() this goes straight to the inner function, since the outer function is self invoked. In a regular JS function it would be like add()(). Therefore add() never touches the var counter = 0 and does not reset the counter and increments the counter through closure .

That self invoked function can only be read once, and the result of the invoked function gets assigned to that variable so var counter = 0 can not be called again (in the same instance) for when we call add it is returning the result of when add was assigned.

Pretty amazing!

In My Own Words: Array.from()

So I’ve just seen Array.from() today in a codewars study group I was giving. We wanted to make an array from 0 to x, and this function will do it for us!

So the first parameter, can either be an array, a string, or the length in the form of an object to set long the new Array should be.

Array.from({length: 5}) will give us an Array with a length of 5, all with undefined.

The optional second parameter is a map function,

(v, i) => i)

v is the value, which we will ignore, and instead will pass in a second parameter i which is the index, and if we return i in our map that will fill in each array with the current index, which will give us the range we wanted!

Array.from({length: 5}, (v, i) => i);
// [0, 1, 2, 3, 4]

Just to show you if we used the value, instead of the additional parameter index we could get this:

Array.from({length: 5}, v => v); 
// [undefined, undefined, undefined, undefined, undefined]

I am so happy to have learned this! It is sooo useful!

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from

In My Own Words: Temporal Dead Zone

Hey, just learned a new phrase today:  Temporal Dead Zone

So just to put it in my own words, so I can try to remember it going forward:
When we create a variable with var in javascript, this hoists the variable and declares it as undefined at the top of the scope, and then when the line of code is hit it will re-assign the variable with it’s value. So if we call the variable name before that line of code that declares the variable, it will return undefined because the variable was created as undefined as explained above

Const and let do not do this,  and the variable is only created with the value (no hoisting here!). So if we would call the const or let above where it was defined we will get an Uncaught Reference error, the variable is not defined. This area above the declaration of the const or let variable is called the Temporal Dead Zone!

Got it? Hope so 🙂

Day 30 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better. And I finally have made it to day 30!! Wow, what a journey!

Today I did: https://www.codewars.com/kata/single-character-palindromes

Time: 8 minutes

What I’ve learnt:

I totally thought this would be impossible! But then I thought about it for a minute, and I was like, hey, that should be easy.

We had three things to check, return “OK” if it is currently a palindrome. That is easy 🙂 string === string.split("").reverse("").join("")

Onto the next challenge. Check if we remove just one letter, will it become a palindrome? If yes, return “return one”.

In a for loop I created a new variable holding the original strings value split into an array (so we don’t obstructively mess up our original array as we iterate), then spliced off the current index (i), and only one element, newS.splice(i, 1). Then checked if it was a palindrome the same way I did above (shoulda made a method for this if I used it twice!) and if it did I returned remove one so that it would break out of the loop since we have the answer.

And the last line says return "not possible" since it has not passed those first two tests.

Score!

What I learned from other people’s code:

I see someone using the do...while. I don’t particularly love their code, but I do like that syntax. It is very readable.

A lot of people made an external function to check if palindrome. That makes sense. Although quite a few actually ran loops to check if it was a palindrome.

Ah, I think if I would have used substring I would not have had to assign to my variable and then remove the letter from it.

I can’t believe I made it this far. It was a great learning journey. I now feel like I can do anything in the world to strings, lol. Have learned new ways to think. Problem solving is coming easier. And I see in how many ways I can grow! Looking forward to an exciting journey as I advance in my programming path. The journey never ends, and the learning never stops!

Day 29 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/help-the-bookseller

Time: 24 minutes

What I’ve learnt:

This was actually a nice challenge. Not too brain twisting, but just a nice problem to tackle.

The first thing I thought to do was to create an object with the category letters (from the second array) with reduce, and Object.assign to give me an object of letters with the value of 0.

I then did a forEach on the through the art array (first parameter), and checked if the first letter art[0] was a key in the object created by the reduce, then I added the price onto it. I was imagining myself in an interview, and thinking if I would go and play with regex to get the numbers out of these strings "ABART 20", "CDXEF 50", "BKWRK 25", "BTSQZ 89", "DRTYM 60" and thought no way, I just went with `parseInt(art.split(” “)[1])` , where I split the string by the space they all had, and just grabbed the 1st index of the newly created array.

Now I have an object with the correct values, but I need to return a string like so: (A : 20) - (B : 114) - (C : 50) - (W : 0)

I used `for (category in categoryObject)` where category gave me the key and `categoryObject[category]` the value. With interpolation I pushed this into an array outside of the for in loop, and after I returned that array with join(" - ").

Flying green!

What I learned from other people’s code:

Again no one liners here (except for one person, but if we copy the code to an editor with text wrap it’s on 5!).

Someone just used a forEach to add to the outer object, and therefore they did not need to worry about returning with an Object.assign. Keeping it simple! Awesome! They also chose to split the string rather than use regex.

I see I could have mapped my last array, instead of pushing it into an outer array and joining that. Duh!

Someone else used alistOfArt.reduce inside thelistOfCat.map to get the string all at once. It’s hard to know what is better to spread out, so each method is doing it’s own thing and what to combine. But great to see how it can be so compact.

 

Tomorrow is 30!!!! Who can believe it?!?!?!

Day 28 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/check-if-two-words-are-isomorphic-to-each-other/javascript

Time: 18 minutes

What I’ve learnt:

It took me a few minutes to comprehend what this exercise was asking for. It wants us to check that each time a letter is used, the value should always be used again in the same place of the second string. And this value on the second string cannot be assigned to any other letter (I only realized this after the extended tests were not passing!).

First things first, if the a and b lengths are not the same, they are clearly not a match — return false and knock that out the door!

I decided the best way to keep track of what the corresponding matching letter on the a string to the b string would be an object. So I defined that object. Then started up a for loop, checked it therelationshipMappingObject[a[i]] does not yet exist && the Object.values(relationshipMappingObject) does NOT include b[i] (meaning it has not yet been assigned to another letter) then let’s go ahead and assign it to our Object.

Then I checked `if (relationshipMappingObject[a[i]] !== b[i])` and returned `false` . If we made it through the whole for loop, then after the for loop without returning false I just put return true.

Green lights! Wohoo! Not as bad as I thought. Took longer to understand what was expected than to code.

What I learned from other people’s code:

One person who did it on one line, I can’t even see what he did! I have moved past being the one liner cool man! 🙂

What others did was iterate through each string (a and b) separately and create an object, with the key being the letter, and the value being the index. Then checking if the second string held those same indexes. I gotta relook at that and see how that accounts for duplicates.

See ya tomorrow!

Day 27 of 30 of Codewars – Javascript

I’ve challenged myself to 30 days of codewars, one a day, time myself, and learn how I could have done it better.

Today I did: https://www.codewars.com/kata/chess-fun-number-1-chess-board-cell-color/javascript

Time: 10 minutes

What I’ve learnt: I knew I was going to have to check the same logic on both cells passed in, I thought creating an external function that would give me the color, then I can just call return checkColor(cell1) === checkColor(cell2)

Now onto the checkColor function! If the charCode of the cell[0] (the letter portion of the spot on the board) is even, we know that if the cell[1] (the number part of the spot on the board) is also even we are on “brown”, otherwise “white”, and the opposite is true if the cell[0].charCodeAt() is odd.

I used two ternaries, inside an if/else, and all was green. 🙂

const charCode = cell.toUpperCase()[0].charCodeAt() if (charCode % 2) return cell[1] % 2? "brown" : "white" else return cell[1] % 2? "white" : "brown"

What I learned from other people’s code:

I see a lot of people used a separate function to check the cell color like I did.

Someone used a bitwise operation `&1` which takes the number and converts it to Binary 1, which means if it’s odd it will return 1, and if it’s 0. I don’t totally get it, and probably won’t use it at this point, but at least I will recognize it. More info is here.

Other than that, it seems everyone used similar logic to mine.

Can’t beleive there are only 3 days left! 3…2…1!

Copyright Loving to Code 2025
Tech Nerd theme designed by Siteturner