Using ES6 Syntax in React

I don’t know about you, but I love the changes made in ES6. I’m currently learning React and ES6 definitely makes life much easier. I’ll talk specifically about Arrow Functions and why using them will help make you coding your components much more fun.

The Olde Way

Let’s take a look at a simple pre-ES6 component.

import React from 'react';

class WhatsUp extends React.Component {
  constructor() {
    super();
    
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick(event) {
    // 'this' is only reachable because of the binding in the constructor above
    // otherwise it would be scoped to handleClick's environment and the log 
    // would be undefined 
    console.log(this.props.message)
  }

  render() {
    return (
      <button onClick={this.handleClick}>Click Me</button>
    )
  }
}

export default WhatsUp

The main takeaway here is the binding of the ‘this’ keyword. Without the binding in the constructor, when we used ‘this’ inside of a function, it would be referring to the functions ‘this’ – not the class.

How the Cool Kids Are Doing It

The cool thing about Arrow Functions is that they don’t bind their own ‘this’. What do the Gods say?

From our friends at Mozilla:

An arrow function expression has a shorter syntax than a function expression and does not bind its own this, arguments, super, or new.target.

Until arrow functions, every new function defined its own this value (a new object in the case of a constructor, undefined in strict mode function calls, the base object if the function is called as an “object method”, etc.). This proved to be annoying with an object-oriented style of programming.

That means we don’t have to worry about binding the function in the constructor. Take a looksie…

import React from 'react';

class WhatsUp extends React.Component {

  handleClick = (event) => {
    // 'this' is not bound to the handleClick function so we can use it freely
    console.log(this.props.message)
  }

  render() {
    return (
      <button onClick={this.handleClick}>Click Me</button>
    )
  }
}

export default WhatsUp

Look at that – we don’t have to use a constructor! Pretty cool. You might think, ‘Eh, no biggie’. But what if we had many more functions that we had to bind ‘this’ to? That’s much more code we have to write and makes our files more bloated. I know if we had to set an initial state, we’d still have to write a constructor. However, we wouldn’t have to bind so many functions.

If you haven’t started using ES6, I strongly recommend it. It will save time and energy in the long run. The Spread Operator is probably what I use second most, after Arrow Functions. Try them out and be amazed! Until next time. Cheers:)

Advertisements

React – First Impressions

My first impressions of React are very positive. AngularJS was the first JavaScript framework I learned and I found it quite difficult to learn. There’s a lot going on in Angular, from controllers to services, routing to factories – it seems much bulkier than React and harder to get up and running initially. Once I actually started building with Angular, I definitely grew to like it. My fondness for React is happening much faster than it did with Angular.

Living in a Declarative World, cuz I am a Declarative Girl Boy

JavaScript is a multi-paradigm language, meaning it can be used for imperative, declarative, functional and object oriented programming. Unlike a language such as Ruby, which is strictly Object Oriented, JavaScript allows programmers to work in much different ways – which is why it has become so popular. So what is declarative programming? What does Wikipedia have to say?

In computer science, declarative programming is a programming paradigm—a style of building the structure and elements of computer programs—that expresses the logic of a computation without describing its control flow.

Ok that sounds pretty cool. But to truly appreciate declarative programming, let’s compare it to imperative programming. I like to think of imperative programming as a micromanaging boss. So when that annoying micromanaging boss tells you to wash the car, it will go something like this:

1. Get a bucket and fill it with soap, water, and a sponge
2. Turn on the hose
3. Take the sponge and start scrubbing the car in circular motion (wax on/wax off)
4. Spray down car with hose
5. Etc, etc…

Yes, thank you Mr. MicroManager, I know how to wash a car. Now let’s look at declarative programming:

Wash the car.

Wait, WHAAAAT?! Where are the rest of the instructions?!? That’s ok – we can trust that the person washing the car knows what to do. After all, that’s their job! I don’t know about you, but I would much rather have a declarative boss.

Ok, so what does this have to do with React? Well, this is how React works! Instead of manually updating the DOM, adding and removing classes, etc., we just tell React what the end result should be and it’ll handle the rest! From stackoverflow:

The benefit of declarative is that you don’t get bogged down in the implementation details of representing state. You’re delegating the organizational component of keeping your application views consistent so you just have to worry about state.

Nathan Hagen

That sounds great, but does this cause any problems? When things are abstracted away, it might give you less flexibility in how things occur. I’m still in the beginning stages of learning React, but I’m looking forward to building something with it. Hopefully I will get to do just that in the coming weeks. Check back next week for my continued trek into the wonderful world of React. Cheers:)

The Sneaky Way to Find a Developer’s Email Address

Searching for a job can be a full time job. I’ve heard this more than once since I’ve started my job search. One of the best ways to get an in at a company is to befriend a developer that already works there. You can research companies online, find your target company, and search LinkedIn for developers that work there. Then what? Well, you have to find their email address and try to connect.

The Standard Way

How I’ve done this up to date, is with a combination of two Chrome extensions: Hunter and Rapportive. Hunter allows you to search any domain and the search results will include many email addresses of the folks that work there. If your target isn’t on the list, no worries – we can see the email format that is used by the company from the search results. Now we can use Rapportive in Gmail to ensure we have the right email address.

Let’s say our target company Apple, the results from Hunter may look something like this:

info@apple.com
steve.jobs@apple.com
tim.cook@apple.com
etc…

If our target is Steve Wozniack, our results from Hunter did not give us what we were looking for. But wait! We can see the format Apple uses and make an educated guess. When composing an email in Gmail, we’ll try steve.wozniak@apple.com as the recipient, and most of the time Rapportive will let us know if it’s a valid email address. We should see something like this on the right hand side of Gmail.

Screen Shot 2017-08-20 at 11.00.12 AM

Not Steve Wozniak…A new app from the creators of Silicon Valley – a follow up to their wildy successful ‘Not Hot Dog’ app

Success! We know the email address is valid! Now we can craft a nice email, ship it off, and wait eagerly for a response. The problem is, I haven’t had much luck with this approach. I’ve sent so many emails out to developers with not much of a response. Enter the sneaky way…

The Sneaky Way

After discussing my job hunt with a seasoned developer the other night at a meetup, he showed me a sneaky way to find another dev’s email address. The only caveat being, they must contribute to open source. My lack of success might be attributed to the fact that I have been emailing company email accounts. The aforementioned seasoned dev told me – better luck will come if you can find their personal email address.

This method all revolves around Github. You can either look up their company on github or google github + the dev’s name. The latter way will ensure you are going to get your target’s email address. Once you’ve found the dev’s account, find a repository they worked on. Make sure it’s not a repo they forked or you’ll wind up with many other email addresses (and not necessarily the email you wanted). Now you’re going to clone the repo, copy it, and head over to your terminal and type ‘git clone ‘. ‘cd’ into the project and type ‘git log’. This should bring up all the email addresses that have committed to the repo.

In my case, however, this just showed me the dev’s names and the commits they made to the repo. Supposedly, there was something wrong with the formatting. Luckily, my new friend gave me a line of code that did the trick.

git log --all --format='%cN %Cgreen<%cE>%Creset' | sort -u

After running this in the terminal, all of the email addresses from the commits to the repo were displayed! Usually, this technique will give us their personal email addresses and we can send unsolicited emails all we want! Evil laugh…

Now to get people to respond. It was said to go as high up as you can in your target company. If there is a CTO – go for them. If not, try a Director of Engineering or a maybe Senior Dev. Keep your email short and sweet. It should only take the recipient 20 seconds or less to read. Include a very brief introduction, a small compliment (I really liked your blog post on such and such), and an ‘ask’ (can I buy you a coffee this week?). If they agree, keep the coffee meeting under 30 minutes and don’t keep them too long – people are busy! Don’t even mention a job. Treat the meeting like you’re making a new friend. If all goes well, they will bring up the topic of a job opening!

Have you had success with this or another technique? Leave a comment below – I’d love to hear about it. If you’re out there in the scary world of job hunting, hopefully this technique will help you! Until next time…Cheers:)

Using a Set For Faster Searching

Recently, I was working on a code challenge at CodeFights which specified that the solution had to run in O(n) time. The brute force solution was a nested for loop, but this would run in O(n^2) time. Here’s the code challenge:

Note: Write a solution with O(n) time complexity and O(1) additional space complexity, since this is what you would be asked to do during a real interview.

Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.

Example

For a = [2, 3, 3, 1, 5, 2], the output should be
firstDuplicate(a) = 3.

There are 2 duplicates: numbers 2 and 3. The second occurrence of 3 has a smaller index than than second occurrence of 2 does, so the answer is 3.

For a = [2, 4, 3, 5, 1], the output should be
firstDuplicate(a) = -1.

Input/Output

[time limit] 4000ms (js)
[input] array.integer a

Guaranteed constraints:
1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length.

[output] integer

The element in a that occurs in the array more than once and has the minimal index for its second occurrence. If there are no such elements, return -1.

My first attempt to solve it worked but unfortunately was not quite fast enough and did not pass the last two tests. I created a new array to hold numbers that were already checked. In a for loop, in each iteration, the new array would be checked to see if the current number was included. If it was, then function would return the number. Take a look…

function firstDuplicate(a) {
    let visitedNumbers = [],
        i;
    
    for (i = 0; i < a.length; i++) {
        if (visitedNumbers.includes(a[i])) {
            return a[i];
        }
        visitedNumbers.push(a[i]);
    }
    
    return -1;
}

If the visitedNumbers array includes the current indexed number in the given array, then that number will be returned. If not, then the number is added to the visitedNumbers array and the next number in the given array is checked. If all the numbers are checked and none of them are duplicated, the function will return -1. Like I said earlier, this works, however it was not passing the last two tests, which I assume had very large inputs. After digging around a bit, I stumbled across something that I had not used before.

According to our friends at Mozilla, a Set is an object that “lets you store unique values of any type, whether primitive values or object references”. Ok, so how does that help us? Well according to this site, the Set method ‘has’ is 16% faster than the Array method ‘includes’. For small inputs, this won’t matter. But imagine a huge input; 16 percent would be very noticeable. Let’s see a Set in action.

function firstDuplicate(a) {
    let visitedNumbers = new Set(),
        i;
    
    for (i = 0; i < a.length; i++) {
        if (visitedNumbers.has(a[i])) {
            return a[i];
        }
        visitedNumbers.add(a[i])
    }
    return -1;
}

Now all test pass! Yay! Apparently this question is asked at Google. That makes me feel good about myself. The moral of the story: Sets are cool and fast. I’ll be using them more in the future. Until next time. Cheers:)

Removing whitespace from a string in Ruby vs. JavaScript

I’m back from vacation. After visiting my family in Long Island, we ventured up to the Catskills for a few nights, which culminated with my younger sister getting married. It was a very cool wedding! The next day, my wife, nephew, and I drove up to Montreal to see her folks. Montreal is one of my favorite cities (in the summer) – it has very European feel. As great as it is to get away, it’s always hard to get back into the groove after a trip. I’m just getting my sea legs back under me so this post is going to be short and sweet.

Have you ever needed to get rid of leading and trailing whitespace from a string? It’s a good rule of thumb to do just that to any input you’re receiving on a form. Luckily, it’s quite easy in most languages. Let’s take a look at how we’ll approach this in Ruby first.

str = "  How's it going?   "
=> "  How's it going?   "
# Let's get rid of that whitespace
str.strip()  
=> "How's it going?"
str 
=> "  How's it going?   "
# We didn't permanently change the string itself
# Most methods are non-destructive, but Ruby let's us be destructive if we 
# really want to. We just got to bang it (pun intended)
str.strip!() 
"How's it going?"
str 
=> "How's it going?"

Pretty simple! Let’s take a look at how to do this in JavaScript.

let str = "  How's it going?   ";
str.trim(); 
'How/'s it going?'
str  
'   How\'s it going?   '
// There's no permanent destructive way to change strings in JavaScript - they 
// are immutable. So we just have to reassign our variable like so...
str = str.trim();
'How\'s it going?'
str  
'How\'s it going?'

I mentioned that strings in JavaScript are immutable. This means the string cannot be changed in memory. So when we call a method like trim or slice on a string, the return value is a new string. Like the example above, we have to reassign ‘str’ to the return value of the method call. In Ruby however, strings are mutable. Let’s take a look.

str = "  Trim me  "
str.object_id 
=> 70365544319940 
str.strip!()
=> "Trim me"
str.object_id
=> 70365544319940 
# Even though we changed the string, the id is still the same
# We can also change characters in place, which cannot be done in JS
str[7] = '!'
=> '!'
str
=> "Trim me!"
# Pretty cool!
str.object_id
=> 70365544319940 
# No change

That’s it for this week. Always remember how cool Ruby can be. It makes life easier in many ways. JavaScript however, can do much more. It is not only an Object Oriented language, but a multi-paradigm language! From Wikipedia:

As a multi-paradigm language, JavaScript supports event-driven, functional, and imperative (including object-oriented and prototype-based) programming styles. It has an API for working with text, arrays, dates, regular expressions, and basic manipulation of the DOM, but does not include any I/O, such as networking, storage, or graphics facilities, relying for these upon the host environment in which it is embedded.

Thanks Wikipedia! Until next time! Cheers:)

Vacation Time

I’ve been on vacation the last two weeks, which included a whole lot of moving around and not much time to think about programming. I don’t think I checked my email for 5 days straight. Honestly, it felt pretty good. Technology is wonderful, but there is a beautiful world beyond the bits and bytes that consume much of our attention.

It’s nice to get a breather every now and then. Coming back refreshed and still realizing you haven’t forgotten much is very nice. I’m still in Montreal until Monday, but wanted to write a little something to keep my blog up. If you haven’t been to Montreal, go now – in the summer! It’s a completely different city during the winter months, which can be quite brutal. I’ll be bringing back the technical part of the blog next week. Until then – happy summer:)

Recursion – It’s Not a Hallucination

Does recursion scare the crap out you? Well, it should! You should stop reading this now, draw the blinds, get in bed and pull the covers over your head. Just kidding! Recursion is pretty cool once you get the hang of it. I’m going to try to break it down for you so you won’t have to run and hide every time it’s mentioned.

From Wikipedia:

Recursion in computer science is a method where the solution to a problem depends on solutions to smaller instances of the same problem (as opposed to iteration). The approach can be applied to many types of problems, and recursion is one of the central ideas of computer science.

Okay, so basically it is a problem that can be broken down into smaller versions of itself. This happens when a function gets called repeatedly by itself until it reaches the stopping point, which is called the base case. So a recursive function is a function that calls itself. Every time the function calls itself, it is looking for the base case. If the base case is not found, the function calls itself again. If you think about it too long, it might make you feel like you’re hallucinating. And down the rabbit hole we go…

Think of it like a for loop, except that the function is sort of flying blind until it reaches the base case.

Enough talk, let’s see an example.

function multiplyUpToFive() {
  // (1 * 2 * 3 * 4) * 5 or
  return multiplyUpToFour() * 5;
}

function multiplyUpToFour() {
  // (1 * 2 * 3) * 4 or
  return multiplyUpToThree() * 4;
}
// and down to multiplyUpToOne()

What we’re doing here is breaking down the problem into smaller problems. That wasn’t a recursive function, but it acts the same way a recursive function does. I’ll rectify this further on. Now for our recursive function, by taking function called multiplyUpTo(n), you can say that the definition of the function is equal to taking the product of

  • the products up to n – 1
  • times n
  • Let’s see…

    function multiplyUpTo(n) {
      return multiplyUpTo(n - 1) * n;
    }
    
    // let's call this with an argument of 4 and see what happens
    
    multiplyUpTo(4)
    multiplyUpTo(3)  // gets called
    multiplyUpTo(2)  // gets called
    multiplyUpTo(1)  // gets called
    multiplyUpTo(0)  // gets called
    multiplyUpTo(-1) // gets called
    // shiiiiiit. Looks like we might be stuck in a recursive loop forever!!!
    

    That function would have ran infinitely because we didn’t add a base case. Think of the base case as the roof of the function. Without it the function will keep going out into space – to infinity and beyond! There’s literally nothing to stop it. Okay, enough analogies. Let’s fix our multiplier function.

    function multiplyUpTo(n) {
      // Our base case is 1, so we'll check if n equals 1
      if (n == 1) {
        return 1;
      }
    
      return multiplyUpTo(n - 1) * n;
    }
    
    // Now if we call our function with 4 as the argument, this is what will happen
    
    multiplyUpTo(4)
    // n does not equal 1, so it's called again
    multiplyUpTo(3) * 4
    // Again n does not equal 1
    multiplyUpTo(2) * 3
    multiplyUpTo(1) * 2
    
    // We reached our base case which is 1 and our function will not repeat forever 

    Now our function knows where it is in the universe and has found its purpose in life.

    Okay, the function has purpose. Now what?

    // Once the function reaches the base case, it will now solve all of the
    // problems it left behind
    
    multiplyUpTo(1) * 2 // 1 * 2 = 2
    multiplyUpTo(2) * 3 // 2 * 3 = 6
    multiplyUpTo(3) * 4 // 6 * 4 = 24
    
    // Once the function has an answer to all of itselves (I think I made that up),
    // then it returns the product the original function call. Woah dude.
    

    If we’re feeling good about our JavaScript we can even use a ternary statement to really make our function compact.

    function multiplyUpTo(n) {
      return n == 1 ? 1 : multiplyUpTo(n - 1) * n;
    }
    

    I like it! Thinking recursively makes you think recursively makes you think recursively. See what I did there. Yeah, I’m a dork. Hopefully this helped you understand the world of recursion. It’s quite fun to write algorithms this way. Although it might be scary at first, don’t worry: The worst that can happen is you float away into the infinite:)