addEventListener() and you!

Event Delegation

What is it? Well I can tell you it is great! Gone are the days of an onMouseOver event watcher on every list item or span on your page. Now you can tell the parents to pay attention to their kids by reminding them to listen to the conversations they little ones are having and reacting appropriately. We do this by using  addEventListener. This brilliant function does just what it says. This one is easier to explain by example, so here goes.

<div id="parent-div">
<span id="child-1">One</span>
<span id="child-2">Two</span>
<span id="child-3">Three</span>
</div>

<script>
// Get the element, add a click listener...
document.getElementById("parent-div").addEventListener("mouseover", function(e) {
// e.target is the moused over element!
// If it was a span item
if(e.target && e.target.nodeName == "SPAN") {
// SPAN item found! Output the ID!
console.log("List item ", e.target.id.replace("child-", ""), " was evented!", e);
}
});
</script>

It is really as simple as that. Now when any child span is moused over the id number for that child will be sent to the console. You can also use specific classes if you use .matches(“className”). Digging deeper into this has me going down the MouseEvent rabbit hole so I know what my next post will be about! I mean who wouldn’t want to learn about MouseEvent.bubbles! BUBBLES!

Importance of Self Documenting Code

What is self documenting code?

Let’s first take a look at code that is not self documenting.

var x = 1;
if (y === true) {
  x += 1;
}

vs 

let count = 1;
if ( loggedInSuccessfully === true ) {
  count += 1;
}

Even though this is a very simple example you can see right away that in the first example it is unclear what x is used for. You may be able to figure it out in context of the rest of the program but you might not.  In the second example it’s much easier to deduce that we are incrementing count every time someone has logged in successfully is true.

Now imagine this was a more complex function in the code.

function z () {
  let x = [];
  let y = _.keys(s);
  tables = _.map(y, function (y) {
    return function () {
       return z(y);
     };
   });
 return sequence(x);
}

vs

function createTables () {
  let tables = [];
  let tableNames = _.keys(Schema);
  tables = _.map(tableNames, function (tableName) {
     return function () {
       return createTable(tableName);
     };
  });
 return sequence(tables);
}

In this slightly more complex example there is only one clue as to what you might be doing in that first function. It’s the keyword sequence and even that just gives you a hint that they might be using the when promise library. This would require that either you wrote the horrible code so you know what it does or a decent amount of time trying to use it with in the code base.

The second one, well it looks like it wants to create a table based off an array of tables using the a function called keys to read the table names from a Schema variable. Then it builds that array by using a function called map to go over the tableNames schema, returning a function that calls the createTable function on the passed in tableName. Then we return the sequence output on that array we just finished building.

Even if that second paragraph does not make complete sense it will let you discuss the function with other programmers or support forums in a more intelligent way. That is the main benefit of self-documenting code, however it will also help you remember what you were doing when you have to revisit the code later.

One of the side effects of self-documenting code are potentially very long variable names. I have seen things along the lines of thisWillBeWhereWeStoreTheResultsOfTableCreationErrors. A bit hard to swallow but I have a pretty good idea what type of data I should expect to retrieve or store there.

Breaking it down

Reasoning

  • Create readable and understandable source code
  • Make it easier on the next guy (or your memory)
  • Keep code cleaner with less comments
  • Keep the documentation inside the code

Practices

The main goal is to make it as human readable as possible. Instead of single word variables use a phrase that is more closely tied to the meaning. The other aspect is to use white space to keep the structure consistent and reduce obfuscation of the algorithm being used.

Gotchas

 

There are things to watch out for, if working with a team, is to maintain uniformity, consistency and to make sure it doesn’t get too far out that it becomes a novel to go through your code.

If you stick to these basic guidelines you will do better than many professional developers out there. If you want to learn more head over to the wiki page.

Maker Square Day 5

Test Driven Development
Write a failing test, then code to the test. Go from Red to Green to Refactor. Why test? It changes the way you think about code. Forces the MVP thought process. Once you have an error, write a test.
Types of Testing
Unit Test – normally focus on 1 single method or class. Unit testing uses faked data.
Integration Test – ensures different parts of system work together like creating a customer, logging in a customer etc.
End to End test – make sure it works in real world test most realistic form of test. Start to finish, whole system. Think about smarter, less tests.
Visual Test – does it look like what it should look like?

 

Maker Square Day 4

Video Lecture on Complexity Analysis. Space = memory. Time = when. How does time grow?

An algorithm is a plan that helps you solve problems.

To compare all numbers is n^2 is of quadratic time complexity.

Find largest by finding smallest? On

if sorted list, compare first and last is constant time. Gives an approximation of time, not an actual number. Note, highest order first. Think about it as LARGE(n).

Static analysis = analyse and reason through it with graphing.

Constant = array look up
O(log n) = binary search
linear O(n) = print array;
O(n^2) = find largest (nested for loops)
O(c^n) = guess password of (n) length

Binary Search?

var binarySearch = function(array, ele, start, end){
  var start = start || 0;
  var end = end || array.length-1;
  var midpoint = Math.floor((end + start) / 2);
  if (array[midpoint] > ele){
    return binarySearch(array, ele, start, midpoint-1);
  }
  else {
     return binarySearch(array, ele, midpoint+1, end);
  }
}

Protoypal Classes

Q: Can you think of a way to use prototype chains that might help? Removes extend loops, allows chaining of values and having them push out.

Talking about obj within constructor class is the same as talking about every instance. To create a function for making instances is a line in that function where you create a new instance object (object.create(car.methods)) an object as a prototype and some logic for augmenting the new object with properties that make it unique from other objects in the same class (obj.loc = loc).

Pseudo-classical Classes

new keyword = when new is used before a function it acts in a special mode called constructor mode. (var foo = func() {blah;}; var blah = new foo;) constructor mode sneaks in the this.object.create(car.prototype); and the return this; at the end of the function. Pseudo-class has two parts, the prototype properties to hold similarities  and the constructor function to hold the differences.

Open Source Lecture

Productivity Tip: Look at OctoTree for chrome and git access

To contribute to open source projects is a good thing! You don’t have to be a genius to help out. Look at the larger repos. Think about clarifying comments, adding tests, even making sure the style is consistent. These things are needed and appreciated.

Tips for success. Follow repo styles and conventions. Pay close attention to the commit message conventions. Changes should be a single commit. Well written merge comments will increase the chance of a successful pull request.

Data Structures

Quick review on scope and closure. Scope = set of rules to define value availability lexical scoping. Closure = if you instantiate an object the instantiated object has access to the original object.

Hash Tables

Very similar to an object. 2 components to a Hash table. The storage part and the hashing function.  The hashing function takes a key, and dresses it up so that its always the same dress for the same key. This hashed key equals the location in storage. We must watch for collisions, and distribute as evenly as possible to reduce collisions.

 

Makers Square Day 3

I don’t know about you but sleep has not been a close and personal friend of mine. Its a love/hate relationship at best tending towards the latter, or is it ladder? I must be tired. It was on Day 3 (dun, dun, dunnnn) that I noticed that I had forgotten to sleep much *cough* is that an owl? *harumph* I am fine, as I was saying an owl has three eyelids: one for blinking, one for sleeping and one for keeping the eye clean and healthy. Wait, I had a segue I was supposed to say, something about night owls…

To The Notes!!!

Best Practices

I have to preface this with a caveat. I really liked this lecture. It made me feel as though I could contribute if only because I enjoy clarity over cleverness. I usually stand in awe of cleverness, but strive for clarity. If that makes sense. Well on to the actual notes.

Save often! Use the auto-save feature of whatever IDE you are in. If it does not have one complain. Only commit to git when working.

Frameworks, when, where, why? (sometimes what?) – It’s a roll your own (smoking reference in this day and age?) vs others. If you really must I would say roll your own, but REALLY look for another solution or you are wasting your time. Let others solve the problems that have already been identified by the community, for now. (A Jedi must have patience)

Modularity

Keep parts together that are related. Avoid bad closure. use input var/let for dependencies, avoid mutating. avoid global. avoid side effects.

Decoupling

Keep unrelated things, unrelated. It sounds obvious but I have found it easy to want to ‘normalize‘ everything. This is the wrong use of normalize, hence the quotes and italics but you will hear it used this way in the real world. They really mean avoid mutating. I see decoupling as breaking the functions down to as small as possible. For the MASH fans out there:

I do one thing at a time, I do it well, and then I move on.
                                                                   –Charles Emerson Winchester III

Abstractions

Hide the guts. Show the usage. It really can be that simple. Think _.each(array, thingToDo); vs

function(collection, iterator) {
  if(Array.isArray(collection)){
    for (var i=0; i < collection.length; i++)
     iterator(collection[i], i, collection);
  } else {
    for (var key in collection) {
       iterator(collection[key], key, collection);
    }
  }
}

Style

Self describing code is better than comments, but comments are better than clever. Follow the company style. Aim for short, compact code. MVP first.

Embrace Failure!

Failure is inevitable, it also indicates you are doing something interesting. Simply put, what is the formula for success? Fail until you succeed.

Common Pitfalls

Failure to read instructions. Read them. Then re-read them. Then.. yeah. Think about the intention.

Formatting

Use 2 spaces instead of tab. White space is your friend. Be consistent. Keep blocks aligned. Avoid redundancy. Keep blocks aligned. Did I mention to avoid redundancy? No? Well do it.

‘use strict’

It was a great day!

Maker Square Day 1

I was pretty nervous starting out. School? Not for a long time now, and even back then I was pretty shitty at it. What would be the difference now? Would I do it? Could I do it? My mind was not on my side, throwing doubts in front of me at every step. So I did what any person I admire has done and said to myself “Do the work”.

I have to admit my notes of the first lecture make no sense to me. Random words of JavaScript, some !!!!s and a whole lotta nuttin.

For Example:

1   -> func(targetClass)

-> document.body.classList
if contains ClassList
add to array
call recurse
results = []
node = document.body
if (node.classlist contains className
push -> results

for ( node.children.length)
function(node.children[i])
get
results = results.concat(node.children[i]
}
return results

({   }).a_prop = { x: 5 }

What the heck is that!?!? I call it insane.js, coming to a github near you…

Maybe I would do better with the second lecture given by Muhammad?

read wiki

Do all toy problems. (sweet toys!)

That almost seems worse! I do slightly better on the next. I can verify this by being able clearly state what I learned. Review underscore/lodash implementation. Intro to Time Complexity. Look at pluck and reduce.

Alright, getting better! The next topic was about Paired Programming and how it was an Agile technique where there is the driver, mostly typing, and the Navigator, mostly syntax/logic. I think with the educational model they focus more on the driver being a bit of a noob and the navigator being more comfortable. In practice it is much more cooperative than that. They mentioned Data Structures very briefly. Then they touched on whats it is like to be a junior (code, code, code, sleep, workout, code) and what it might be like to be a senior (code, code, code, code, code, jobs, code, code). I am pretty sure they said much more but… I learned that we had to do 5 min presentations and I got excited about that.

Can’t wait for more!