JSMandelbrot: Exploring Fractals with HTML5

I recently wrote a JavaScript toy to explore the Mendelbrot fractal set using JavaScript and the HTML5 Canvas API.

Visit it here. (Warning: loading the page is CPU intensive. You’ll want to wait until it says “Done” in the lower-right corner until you can zoom in.)

frac

From a web developer’s standpoint, JSMandelbrot is a pretty interesting demonstration of the power of the Canvas API and explores the limits to which mathematical computation can be safely deferred to the client.

From a geekier standpoint, fractals are just plain cool. I’ve spent close to hours zooming in on various sections of the set. The infinite vastness of the fractal is mindboggling and wonderful.

From my personal standpoint, since high school I’ve had an interest in Mandelbrot fractals. I can remember watching a public television documentary on them. I was so excited by the show that I asked my AP Calculus teacher (who actually took a class on fractal geometry when she was in college) to help me figure out how to make them on my own. She told me that they were too complex for me to learn. This fanaticized my interest in them and a few weeks later, just based on my own online research, I had a Mandelbrot generator on my TI-83 Plus graphing calculator and shortly thereafter I implemented one in QBasic on my computer. It was through this experience that I came to know for a certainty that I wanted to be a programmer.

I hope you enjoy it!


Updates to Validity and Roadmap

I’ve gone through and updated the Validity documentation plus plenty of tweaks here and there to the whole site. Check it out!

The next steps for Validity itself are:

  1. Improved support for radio buttons.

    It seems like most of the problems I’m helping people with have to do with radio-buttons. Consequently, we’ll be adding tools to validity to make this validation as straightforward and helpful as possible.

    We feel that it’s important for using Validity to feel natural, and radio-buttons are an area that can be improved a bit.

  2. Improved support for password validation.

    We’re planning to introduce a semanticPassword validator. This will allow you to specify the complex validation parameters needed for passwords (such as minimum non-alphanumeric characters, password strength, etc.) in a manner that makes sense.

    The goal is to make the way you validate a password on the server the same as the way you do so on the client. If, on the server you specify the minimum number of non-alphanumeric characters with an integer value (such as commonly in ASP.NET) you won’t have to translate that into a regex for validity. A regex would be less manageable. Less manageable is bad.

They’re exciting times for Validity. Look for a new version soon!


Give Your Page Subtle Style With Ligature.js

Although I’m not very good at it, I’ve always enjoyed typography. A few years ago, a very good math professor at Portland Community College got me started in LATEX programming. Ever since then I’ve sort of had an appreciation of the subtler side to good type.

One of my favorite parts of LATEX is how it automatically converts normal text into ligatures. Ligatures, if you don’t know, are essentially two letters that get typographically mashed together into a single glyph. For example, a ligature exists for the letters f and i, forming fi. (Check it out. That fi is a single character. Try selecting just the f.)

Most printed books use ligatures when they’re typeset. Most computer text (for instance a document typed out in Microsoft Word) however, would not use ligatures. The result of this, at least the way I perceive things, is that ligatures grant text gravitas. My eyes are trained to take text with ligatures more seriously.ligature.js

Enter Ligature.js, the fruit of less than an hour of JavaScript hacking. Easy to write as it may have been, I’m proud of this little script.

You might have already guessed what this script does. Ligature.js will crawl over an HTML Document and insert ligatures where it finds corresponding character sequences. In fact, it’s already been run on this blog page! (If JavaScript is enabled in your browser, that is.)

The implementation is nothing fancy. There’s a recursive node-crawler algorithm which will use regular-expression find-replace logic to insert the ligatures. See the code page (liked above) for all the usage info.

In fact: Ligature.js is so compact, it can even be stored as a bookmarklet so that you can bring the wonder of typography to any website! Just bookmark this link, and you’re good to go!

Enjoy!


Is AdBlock a Must for Netbooks?

I have an Acer Aspire One D150 Netbook, and I love the thing. I use it to surf the web, take notes in class, program, read, write, watch videos; it’s a great machine.

netbook

But recently, my browser has been slowing down on account of the increasing number of heavy advertisements in the sites I visit. (Particularly flash-based ads.) These ads have gotten so frequent and heavy that they even manage to halt my browser altogether.

This isn’t at all surprising. My netbook, like most of them, has rather weak graphics capability. Added to that, the ads I’m grieved by in particular are the ones involving automatically playing video and flashy transition effects. It’s not hard to see why this sort of thing would slow my computer.

First of all, I think it’s worth appreciating the irony that a machine designed for surfing the net (a *net*-book as they say ) can’t quite accomplish this task. Alas.

The obvious solution to this issue is to install the very-effective Ad Block Plus plugin for Firefox. Bang! No more ads.

However, I haven’t been using this plugin already for minor-ly ethical reasons. Blocking ads on a site feels like a minor act of theft to me. I like finding good content on the web, and consequently I’d like the creators of good content to be supported. I certainly don’t want to sound judgmental of people who use Ad Block Plus. This is just why I haven’t been using Ad Block myself.

The point I’m trying to make here is this:

  • Netbooks locking up on account of overweight ads takes the use of Ad Block Plus out of the realm of media-ethics and makes it a matter of usability.

When the online advertisements get too big, no-one wins: I have to be a bad citizen of the internet, the advertisers’ ads aren’t being displayed and content generators don’t receive ad revenue. The Ad Block plugin, then, is a sorry compromise.

(Besides: I’m certainly not going to click on any of the stupid ads anyway.)


Strange Behavior of the Global Regex Flag

So, for some time I’ve been building a jQuery plugin called jQuery.validity. I’ll post more on that later, but suffice it to say for now that the plugin uses regexes to examine the format of strings. A few days ago, Jeff (another of the Validity developers) caught Validity acting strangely when he used it with some custom regexes.

What was happening was the regex would give seemingly random results testing whether the the same string with the same regex. This would result in Validity allowing invalid inputs and disallowing valid ones: pretty much the opposite of what it’s supposed to do.

Eventually, we discovered that the problem was related to the the global flag that he was applying to his regexes. Removing the global flag caused the regexes to act the way we would expect them to.

Validity worked again. I added notes to the documentation entreating developers not to use regexes with global flags. This is okay, I guess for a temporary solution, but I wanted to actually solve the problem and understand where it was coming from.

The following code snippet illustrates this strange behavior:

var
    // Regex to search for the word duck
    // without the global flag set.
    nonGlobal = /duck/,

    // The same regex,
    // except with the global flag set.
    global = /duck/g,

    string = "duck duck goose";

// Use the regex to test the string:

nonGlobal.test(string); // True. 

// We can test these two as many times as we like.
// This regex tested against this string
// will always return true.

nonGlobal.test(string); // True.
nonGlobal.test(string); // True.
nonGlobal.test(string); // True. 

// However:

global.test(string); // True.
global.test(string); // True, again.
global.test(string); // False!?!?
global.test(string); // True again!
global.test(string); // True.
global.test(string); // Now we're back to false.

// This global regex,
// tested many times against the same string
// will not always yield the same result.

To Jeff and I, this behavior seemed like JavaScript was misbehaving (even though we got the same strange behavior in all browsers). It seemed to us that one regex tested against one string should elicit the same result every time.

I set forth to research the topic. When I finally figured out what was going on, it turned out that we both had incomplete understandings of how regexes were supposed to work in JavaScript.

(Well, we won’t take all the blame. My feelings are that good, complete documentation on how JavaScript handles the global flag is hard to find and confusing when you do find it. In this article, I’ll try to lay it out as clear as possible.)

What Exactly is the Global Flag For?

Simply put, the global flag tells regexes to find and capture all possible matches in a string (not just the first one). The global flag is only useful when you attempt to capture matches out of a string, not when you’re testing a string’s format.

(Really, JavaScript only supports three regex flags. Before doing research on this problem I didn’t really know exactly what they did. I’ll cover them in what I believe to be plain terms in this article’s appendix.)

What Does JavaScript Do With a Global Regex

Normally, the global flag is useful for the “regex.match(string)” method, which will return an array of matches. However, if one is not attempting to locate matches, the global flag will still affect the “regex.test(string)” method!

If the regex is global, then “regex.test(string)” will only examine the string so far as the conditions of the regex are satisfied, and then return true. But, it will also set the “regex.lastIndex” property to the character index of where the examination stopped. When “regex.test(string)” is run a second time, it will examine the string starting at “lastIndex”. This will happen even if you’re testing of a totally different string, of any length!

What Happened in the Example

As you can see in the code example above, the first time “global.test(string)” is run, the global regex found the word “duck” within the string, then saved the “global.lastIndex” property to “4”.

The second time the test is run, JavaScript started from position four and found the word “duck” a second time returning true. At this point “global.lastIndex” is equal to “9”.

The third time the regex is run, JavaScript started from the ninth position and encountered the word “goose” followed by the end of the string. Since “goose” does not match the regex, false is returned. However, since the end of the string was reached without satisfying the regex, “regex.lastIndex” was set to “0” effectively restarting this unpleasant ordeal at the beginning of the string.

As you might have guessed, the next two tests would return true, followed by a false on the third.

It’s possible that this mechanism was meant for iterating over matches within a string, but that functionality would seem to make more sense in the “regex.exec(string)” method than in “test”.

(It’s my opinion that the test method shouldn’t be doing this. Test means test! It’s testing! Not iterating or finding matches. Testing!)

The Solution

The solution to this dilemma is painfully simple, if the regex is global just set the “lastIndex” property to zero before you test. Observe:

if (regex.global) {
    regex.lastIndex = 0;
}

That was easy. I put this code into Validity so that it will execute this before it uses a regex for testing a string. In this way Validity will be able to make use of regexes that have global flags.

Conclusion

The morals of this story are:

  1. Only use the global flag (“/g”) on your regexes if you’re actually going to be finding several matches within a string.
  2. If you use a global regex for testing anyway, enclose it with the anchors (“^” and “$”) so that either the whole regex will be satisfied or not.
  3. If you don’t use the anchors, at the very least, set the “lastIndex” to zero before you use a global regex to test as string.

Appendix

I feel that most of the documentation and tutorials that cover regexes in JavaScript don’t explain flags terribly well. Here, I’ll attempt to explain them concisely and clearly.

The three regex flags that are supported by JavaScript’s regex engine are:

  • /g: As we’ve seen, this flag will instruct the regex engine to search for all possible matches within a string. In some cases, it will cause the engine to behave iteratively.
  • /i:This flag enables case-insensitivity. Using this flag is a simpler way of allowing upper and lower case than using bracketed groups.
  • /m: This flag enables multiline searching. Specifically, what it will do is cause the “^” and “$” anchors represent the start and end of the entire string rather than just the start and end of the first line.

Welcome

Welcome to the That’s Captain to You blog! At this place I plan on writing about things I find or am working on. Likely, most of it will be related to web development and design.

A quick, tiny autobiography: I a student finishing up my Computer Science degree in Oregon. I work as a programmer at a software company that deals mostly with ASP.NET web-applications.

I also manage a open-source jQuery form-validation plugin called jQuery.validity. I do a lot of work in JavaScript.

Anyway, my hope with this blog is that I’ll be able to supply information which will be useful to somebody. Enjoy.