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:)

Advertisements

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:)

    How to Clone a Website Using Chrome’s Dev Tools Part III

    Alrighty then! We’re going down the home stretch. Let’s take a look at our remaining errors.

    Screen Shot 2017-07-07 at 4.01.48 PM

    Much better!

    And this is what our clone looks like…

    Screen Shot 2017-07-07 at 4.04.47 PM

    This is what Carbon Five’s site actually looks like…

    Screen Shot 2017-07-10 at 10.37.59 AM

    Right off the bat, we can see that our fonts are not the same and we need the Carbon Five logo. Looking at the errors above tells us the same story. Let’s dig in and tackle each one of these errors. The first error is for a JS file called ‘v2.js’. After searching our index.html file, we’ll find the JS file being referenced in the footer as:

    <script charset="utf-8" type="text/javascript" src="//js.hsforms.net/forms/v2.js"></script>
    

    All we have to do is prepend the src link with ‘http:’. After refreshing our index.html file in Chrome, the error is gone. Easy peasy:) Next on our error list is for ‘file:///fonts/c5-logo.woff’. If we search our index.html file, we’ll find two lines of code referencing the styles for the font/logo. So that means we’ll search the app.css file. We’ll find this block of styles:

    /* c5 icon font styles */
    @font-face {
      font-family: 'c5-logo';
      src:url('/fonts/c5-logo.eot');
      src:url('/fonts/c5-logo.eot?#iefix') format('embedded-opentype'),
        url('/fonts/c5-logo.woff') format('woff'),
        url('/fonts/c5-logo.ttf') format('truetype'),
        url('/fonts/c5-logo.svg#c5-logo') format('svg');
      font-weight: normal;
      font-style: normal;
    }
    

    Let’s go check the sources in our console at carbonfive. When we click the images folder, there are two files – c5-logo.woff & pentel.woff. The ‘woff’ extension stands for Web Open Font Format. This file type for fonts is compressed so websites using these file formats should load faster. We can append ‘/fonts/c5-logo.woff’ to ‘carbonfive.com’ in Chrome and the file will download to our computer. All we have to do is make a ‘fonts’ folder in Atom and drag our recently downloaded file over and drop in. When we refresh the browser we’re still getting the error. So we probably have to change the way it’s being referenced.

    Let’s prepend all of the urls from the c5 icon font styles above with ‘..’. This will bring us up two the root directory and then we’ll be able to access our fonts folder. Let’s refresh Chrome and see if we’re down a couple more errors. We are! We only have three errors to go:)

    Screen Shot 2017-07-10 at 11.12.44 AM

    Two of the errors look very similar to the ones we just took care of. Let’s try the same steps. First, append carbonfive.com with ‘/fonts/pentel.woff’ and open in Chrome. That should download the file. Next drag it over to Atom and place in the fonts folder. Now let’s do a search in our app.css file for ‘pentel’. We should find this block of code:

    
    @font-face {
      font-family: 'pentel';
      src:url('/fonts/pentel.eot');
      src:url('/fonts/pentel.eot?#iefix') format('embedded-opentype'),
        url('/fonts/pentel.woff') format('woff'),
        url('/fonts/pentel.ttf') format('truetype'),
        url('/fonts/pentel.svg#pentel') format('svg');
      font-weight: normal;
      font-style: normal;
    }
    

    Looks very familiar! I think you’ll know what to do next. If you said ‘prepend the urls with two periods’, you are correct! After refreshing the browser we’re left with one error! Sweet!

    **Just a note – the ‘pentel’ font is an Adobe font, which you’ll need a typekit password for. This is not a free font. It will work locally, but if you publish to github pages or something similar it will break.**

    The last error has something to do with a Google API and from the look of the link, it’s specific to Carbon Five. This means only their devs have access to the API. In that case we’re done! Feel free to change images, fonts and styles. If you see a cool feature, try to figure out how they’re doing it – you have the code in your hands! I hope this was enjoyable for you. If you’re ever on a cool website and you want to see what’s going on under the hood, command + option + i. What did the world look like before Dev Tools? I don’t want to know!