Get Computed Style in JavaScript

The computed style of an element incorporates external CSS (via stylesheets), inline styles and styles prescribed via JavaScript. It’s most commonly used to get the default style of an element if it’s not specifically assigned via styles, i.e. the default style that the browser gives an element. It’s a very undocumented part of JavaScript engines, and, of course, there are multiple implementations. For more details, read this blog post.

For my Linkurious project, I needed to get the computed style of an element in a cross browser way. I came up with an implementation that works in every version of every browser (within reason, the C64 is not supported), and is easy to use.

I’ll leave the details of how it works as an exercise to the reader. I will say that this is a good example of how to use a closure to improve the efficiency of a function. Notice that the cross-browser garbage is only executed once, not on each call.

//must be executed on or after the domready event, since it (may) require document.body to be non-null
var getComputedStyle = function() {
  var func = null;
  if (document.defaultView && document.defaultView.getComputedStyle) {
    func = document.defaultView.getComputedStyle;
  } else if (typeof(document.body.currentStyle) !== "undefined") {
    func = function(element, anything) {
      return element["currentStyle"];
    };
  }

  return function(element, style) {
    return func(element, null)[style];
  }
}();

//and use like so:
getComputedStyle(document.getElementById("foo"), "display"); //might return "inline-block"

April 5, 2010   Posted in: javascript, web development  No Comments

Linq Walk

So, we all know Linq is rad. Not in that silly faux-SQL syntax, but in the manly, declarative, fluent syntax.

But the sad part is that there is no walk extension method. Walk is a functional programming staple that iterates over a collection of stuff and applies a callback to each one. In PHP, there is array_walk, in JavaScript there is each.

You might be thinking, “but there is a ForEach() extension method on List!”. And you would be wrong, because there is a subtle, yet important difference between IEnumerable and IList.

IEnumerable is late-binding. That means you can do whatever you want to it, but execution is deferred until you actually enumerate the enumeration, i.e. using a foreach construct. In a list, there is no deferred execution. This deferred execution is accomplished through the magic of closures and expression trees. Read up on them.

In the meantime, here is a fluent implementation of walk:

public static class LinqExtensions {
	public static IEnumerable<T> Walk<T>(this IEnumerable<T> source, Action<T> action) {
		foreach (var t in source) {
			action(t);
			yield return t;
		}
	}
}

You can prove that this is in fact using deferred execution with a simple test:

class Program {

	class Foo {
		public int Bar { get; set; }

		public override string ToString() {
			return string.Format("Foo(Bar={0})", Bar);
		}
	}

	static void Main() {
		IEnumerable<Foo> foos = new[] { new Foo { Bar = 2 }, new Foo { Bar = 1 }, new Foo { Bar = 3 } };

		Console.WriteLine("IEnumerable.Walk():");
		foos.Walk(Console.WriteLine);
		Console.WriteLine();

		Console.WriteLine("List.ForEach():");
		foos.ToList().ForEach(Console.WriteLine);
		Console.WriteLine();

		Console.ReadLine();
	}

}

The output looks like this:
linqwalk

Notice that nothing got printed the first time through, using the Walk() extension method. There’s your deferred execution. That means our extension method did not enumerate the enumeration, so it’s safe and efficient to use walk in a normal linq expression where you are depending on deferred execution, like this:

IEnumerable<Foo> foos = new[] { new Foo { Bar = 2 }, new Foo { Bar = 1 }, new Foo { Bar = 3 } };

Console.WriteLine("Doing more stuff:");
var listOStuff = foos
	.Where(foo => foo.Bar >= 2)
	.Walk(foo => foo.Bar += 10)
	.Select(foo => new Baz { Foofy = foo })
	.Walk(baz => baz.Foofy.Bar--)
	.OrderBy(baz => baz.Foofy.Bar);

foreach (var stuff in listOStuff) {
	Console.WriteLine(stuff);
}

Console.ReadLine();

linqwalk2

Well, maybe that’s not “normal.” Whatever.

March 24, 2010   Posted in: c#  One Comment

Sudoku Solver: 2006-style

College was such a carefree time. I wasn’t jaded, or cynical, or experienced (at least not in the way you’re thinking). I didn’t care about testability, or code coverage, or documentation, or design patterns, or any of the crap that plagues my thoughts whenever I sit down to write code. I would just sit at my computer, fire up ye olde JPad Pro and churn out steaming mounds of code.

steamingmoundsofcode

I recently found a cool thing I created while in college: a Sudoku solver. It’s nothing new or innovative, but it is coolish looking. And it’s a Java applet! Remember those?

It might just be amusing to look at the HTML source and laugh at my foolish naГЇvete. No doctype? Not quoting HTML attributes? 1998-style mouse rollovers? JPEGs? Not using swing? The futhermucking <applet> tag!? You might have to see it to believe it.

Be delighted.

Stay cool over the summer, guys.

PS: on a more up-to-date note, I had to change the name of the isValid() method because it was causing NullPointerExceptions during the panel/applet init phase. I guess the order of method calling changed since 1.4?

PPS: obviously I shouldn’t have been overriding Component.isValid(), but I didn’t know what I was doing. I was only 20!

March 9, 2010   Posted in: java, lulz  No Comments

Uncountable vs. Infinite

What does it mean to be infinite? Never-ending? What about uncountable? Is the set of integers uncountable? How about the real numbers? What’s the difference?

Questions from a freshman math student, no doubt. The uncountable vs. infinite problem is a turning point in the quest for a bachelor’s degree in mathematics. To be crude, it’s the “shit or get off the pot time” for the aspiring undergrad. It’s also one of the coolest definitions in mathematics, because it’s paradoxical and basically impossible to explain without also proving it. Not very many problems are like that.

This problem has to do with the cardinality of sets: “prove that such-and-such set is countable”. Not surprisingly, this comes up a lot in discrete mathematics and group/ring theory, since both topics use sets as input and output to problems.

Infinitude

So what does it mean to be infinite? That’s actually the easy one: it goes on forever. The set of integers is infinite, because, for example, there’s no upper bound on how high you can count. The natural numbers [1, 2, ... n-1, n, n+1, ...] are also infinite, for the exact same reason. Yet it seems like the natural numbers should be half the size of the integers, since it’s really just the set of integers without the negative ones. Yet both sets are infinite, and we still have \mathbb{N} \subset \mathbb{Z}.

So we have two infinite sets, and one is a subset of the other. We already have a paradox, and I haven’t even gotten to countability yet. Isn’t math fun?

Countability

So, how is uncountable different? Well, actually, the definition of countable is really the interesting part here. The formal definition of countable is:

A set is considered countable if it is isomorphic to the natural numbers.

Like any good mathematical definition, it leaves you searching for a dictionary. Basically, it means that a set is countable if you can come up with a function that maps every element in the set to a distinct element in the natural numbers. If you think about that for a minute, it kind of makes sense. The natural numbers are also known as “the counting numbers”. If you can represent another set as a function that maps to [1, 2, 3 ...], then you’ve just proven that it’s fundamentally equivalent to the counting numbers, so it should be countable. Of course, a proof by grammar isn’t really acceptable, but for the purposes of comprehension, it might help. Or not. Whatever.

So, obviously, the natural numbers are countable, because the function f(x)=x|x\in\mathbb{N} maps every element x in the natural numbers (\mathbb{N}) to itself.

Diagonalization

Now, we come to Cantor, and his proof by diagonalization. Basically, Cantor came up with a simple of way of expressing the countability of sets using a matrix where the diagonals of the matrix are significant. But the theory of that is not important right now. Right now we’re going to use diagonalization to prove that the rational numbers (\mathbb{Q}) are countable.

Let’s put the rational numbers in a matrix, such that the pattern is obvious.

\left( \begin{array}{ccccc} 1/1 & 1/2 & 1/3 & 1/4 & \ldots \\ 2/1 & 2/2 & 2/3 & 2/4 & \ldots \\ 3/1 & 3/2 & 3/3 & 3/4 & \ldots \\ 4/1 & 4/2 & 4/3 & 4/4 & \ldots \\ \ldots & \ldots & \ldots & \ldots & \ldots \\ \end{array} \right)

If the pattern’s not obvious, we’re enumerating the rational numbers, starting in the top left corner with 1/1. To the east, the denominators increment, and to the south the numerators increment. By enumerating the rationals in this way, it should be equally obvious that given an infinitely large matrix, we would generate every single rational number. For example, where would 117/934 be? It would be at the intersection of the 117th column and the 934th row.

Now, Cantor’s diagonalization comes in to prove that the rationals are countable. If we use a pen and traverse the matrix starting at the top left corner at 1/1, we can traverse it in such a way that our pen never leaves the table, and we hit each number only once. This graphic should help visualize it:

diagonalization

QED.

How does this prove that the rationals are countable? Well, we just showed that we can enumerate every single rational number, and traverse them in a unique way such that we only hit each rational number once. There’s your isomorphism. If you really want, you can put that sentence in the form of a function, but I’ll leave that as an exercise to the reader.

February 27, 2010   Posted in: math  No Comments