Friday, October 16, 2015

Remove dupes from Javascript array

So imagine you have an array with a bunch of values, and you want to remove all of the duplicate values. There are a lot of different ways to do this... I was trying to come up with a way to do this without creating a new array. I was thinking that Array,indexOf() is probably just a loop that runs though an array from 0 until the end. If this assumption was true, I could catch dupes by looping through backwards, and checking if indexOf is not equal to the current iteration. This way I have a loop running from length to 0, and a built in loop running from 0 to length. Turns out, I was right. Here's the code.

And a JSFiddle Demo!

Sunday, August 23, 2015

Recursive Functions in real life

Recursive functions are one of those things that seem to only occur in hypothetical situations. Well this week I wrote a real life one for a good reason. The goal was to create a dynamic HTML tree structure with an unknown number of children, grandchildren, great-grandchildren, etc. Each parent would be a LI inside of a UL. All children would be contained in their own UL, with child LI's, and keep on looping...  The goal was to look like this: but build the HTML dynamically. Here is how I solved it in Asp.NET C#.

I get a list of all of the Ids that will be used, so if the user selects a hierarchy that is Id 1, Id 2, Id 3, my list will contain [1,2,3]. I pass this list into my LoopParams function, and use an iterator to figure out which Id I am going for. I can then use iterator + 1, to get at the next Id in the series. This allows me to continue querying for the next available Ids, and if they exist, add a new UL and child LI's. If they don't exist, I just add the one LI and move on to the next parent.

The end result was something like this, which changes dynamically as each "Function Type is selected:


Sunday, May 31, 2015

Java if vs. Javascript if.

Not all if's are created equal. In Java, you really have to detail exactly what you want to check for. If you put anything inside of an if that's not a boolean comparison, you get an error. Since everything starts out as null, you spend most of your time in Java checking for null (myVar != null).

However, in Javascript, you can do all kinds of fun things with an if!

Clearly the JavaScript if is doing more than simply evaluating boolean expressions. It inherently checks for undefined, null, "", 0, NaN, or false, as well as the classic uses of an if.
This begs the question... Why can't the Java if be more like the JavaScript if? Thousands of checks for null could be removed if the Java if inherently checked for null when presented with a Object.