Tag: JavaScript

Easy visual identification of git short sha’s.

January 9, 2019 » Geek

For a recent pet project at work I had to display a bunch of git short shas. Most of the time, these shas should match each other, and it is important to be able to quickly glance at them and evaluate if any of them are not the same.

Sure, you could count on your eyes to just notice the characters don’t match, but short shas are drawing from a limited alphabet (16 characters) and we would only be adding more shas to the listing over time, so noticing one abberant item would get harder over time.

The solution I landed on was to drop the final character of the sha and use that as a hex color string. While this is imperfect, it works remarkably well.

To make the sha readable over the color I needed to find a contrasting color. To keep it simple, I took the average of the individual channels, and if it was over 128 I used black. Under 128 I used white.

Here’s a little snippet of the JavaScript I wrote for this:

This could be improved by using luminosity measures designed for eyeballs instead of a rough mean of the colors, I could constrain the colorspace for shas to throw out colors that are problematic for color blindness, etc. I’ll leav e that as an exercise for the reader.

Tags: ,


November 12, 2013 » Consume, Geek

Update (2014-02-10): I forked an existing mini-campfire chrome extension and added some tweaks of my own. That is what I use now. You can get it here; github.com/jmhobbs/mini-campfire-chrome

I use Campfire in my browser, and I often run multiple rooms side by side. This gets crowded in each browser window, so I made a bookmarklet to easily trim out the extra UI. It drops the sidebar and header, and widens the remaining elements. You loose some functionality, but I find I don’t really need it. A refresh will restore it to normal.


You can add this to your bookmarks bar by dragging this link to the bar: ThinFire

Impromptu logging from a socket.io connection

October 27, 2012 » Geek

I recently participated in a live streamed event that provided a “watching now” counter usin socket.io. Basically it was a super simple node.js script which incremented or decremented a variable when users joined and left the channel, and broadcasted the count to it’s subscribers. What I didn’t realize until right before the event that we might want to have a record for users on page at a given point in the broadcast. With so little time before the broadcast, I didn’t want to tinker with the server and break it, so I did the next best thing, I logged from the subscriber side.

I put up a quick PHP script on my laptop that allowed cross-domain access from the origin server and logged the incoming counter.

Then, in Chrome’s JavaScript console, I just hooked updates from socket.io into an XHR to provide the values to my PHP.

It worked like a charm, I didn’t have to mess with the server at a crucial point, and we got the data we needed.

Reading Code: Drew Gourley’s Countdown Script

April 17, 2012 » Geek

A core step of growing as a programmer is reading code. I claim to be a fan of reading other peoples code, but I never seem to do it. Yesterday the excellent @DrewGourley tweeted about some code he deployed on the (gorgeous) new MahaMusicFestival.com.

Since I enjoy Drew’s work (the Oxide site has lots of really neat stuff), but I’ve never really read any of it, I thought I’d give some code reading a whirl. As a little experiment I’ve decided to transcribe my thoughts through the entire reading process; I’m typing it as I read.

This may turn out scattered, but it will show how I read code, and hopefully poke a little hole of insight into Drew’s code.

Note: The code on Maha has since changed, and probably will in the future. For reference I’ve saved off a copy of the code I read, so you can follow along if you’d like. Please recognize that this is not my work, it’s all Drew and the Oxide crews’ – maha.js.

Also, I went back and cleaned up some grammar and spelling errors, but for the most part this is verbatim what I wrote as I was reading.

The Code

So the product I’m going to poke around in is the countdown timer on MahaMusicFestival.com – going there to check it out I find this cool piece.

And, the slick part is this great number animation, which I have captured for posterity here.

So let’s find the source for it. Popping open view-source I quickly find a script tag for http://mahamusicfestival.com/wp-content/themes/maha2012/js/maha.js in the header. Since every other script tag there is for something generic (jQuery, Modernizr, etc) I’m guessing this is it. Also it looks like the site is based on WordPress – it’s amazing how flexible themes can be.

Clicking over to that source I see it’s a collection of JavaScript bits for the site, wrapped in a jQuery ready event.

That’s a nice, and very correct way of using jQuery for page load. I’m usually lazy and just do this:

I should probably up my game a bit there, huh? Just in case another library has taken over $ onload of my scripts.

Scrolling down I see some relevant functions that are all prefixed with Oxide, like OxideSlider.

My first thought here was “namespace pollution!”, but then I realized that this is all encapsulated in that ready closure, so it’s good to go.

Lot’s of stuff I could look at here, but I’m on a mission: coundown code. Browsing down I find my target. Lines 87-208 seem to be what I’m after. I’ll deal with this in chunks now.


First thing up is the variable declarations. Nice and orderly.

I see a few things here. First, I like the notation of $dayspan – prefixing variables with $ is a good way to visually identify jQuery objects, sort of a Hungarian Notation for jQuery.

Second, I’m a bit skittish of d, h, m, s, go and di. I can instictively identify what the first four are (day, hour, minute, second) but the last two elude me. I’m sure this will become clear as I read on, but since it feels weird to me I guess that means I like my variable names a bit more descriptive. Learning about myself through others!

Core Function

Up next appears to be the core function of which this all revolves around, OxideCountdown. And it’s a doosie, so I’m going to try and chunk it out in pieces.

First up are some variable assingments. Interestingly d, h, m, s are not integers, that’s what I was expecting. This function might hold some surprises for me!

So, this next chunk seems to be pulling the current values out of the spans, one at a time.

Interesting use of parseFloat here, as I would have expected parseInt. Could this be related to the bugs in interpretation by parseInt?

So, it works it’s way through each time span, grabbing the value of the each digit in order and pushing it onto the corresponding array, so that each array would read out the same as the visual version, i.e. today d = [ 1, 1, 6 ];

Also, it’s interesting to see that go seems to be an accumulator, but I’ve not figured out what for yet. It’s just incrementing with all the values of all the digits, which doesn’t seem useful to me. i.e today go would equal 8 (1+1+6) after the $dayspan.each. My curiosity is piqued!

Okay, on to the next chunk!


So here’s the next block, I warn you it’s a bit hairy!

So I’m now seeing that di is how many digit’s will be displayed in the days area? I’m lost now, I was operating on the assumption that each section has a fixed number of elements in it. Let’s jump to the HTML real quick…

So yeah, I suppose it’s possible that days might not have all those spans in it, but that seems true of all of the blocks if we are going down that route. Hopefully reading more will shed some light. But first, let’s double back and look at the math a piece at a time.

Looks like this will be called once a second, and will decrement the right-most seconds column by one second (the reverse indexes here could get confusing).

It seems that the rest of this section is just balancing the carry for that subtraction. Here’s the seconds code, but I stuck in comments where I heard them in my head. The pattern repeats up until we hit tens of hours.

Now that we have an underrun on tens of hours we have to tinker with days. So there is what di is for! Since the number of spans for days is (apparently) flexible, we are going to use the length of the days array to access the largest element. Makes you wish JavaScript was allowed negative indicies on arrays (d[-1]), but that would of course break [] object notation for the key “-1”, which as we all know is super useful ;-p

The loop that follows just does the same carry algorithm on all the days blocks.


At this point I noticed something I thought might be a bug. In the tens of hours decrement block I saw that h[0] is set to “5”. I’m not sure that is possible, since there are only 24 hours in the day, so it seems that at midnight a tick would mess up the count. I’m set up a quick test script for this, since I don’t want to stay awake until midnight watching :-)

After running it, I got bad output, sure enough.

Corrected code would be this, which actually reaches backwards into h[1] to fix it.

Update: I shot Drew an email and he fixed it. He even gave me credit!

Moving On

Ah ha! Now I finally see what go is for!

It’s an accumulator to know when to stop this whole thing! Evidently there is a timeout set on timer, which we haven’t seen yet.

When all the digits in the countdown are 0, the accumulator is also 0. Tricky!

I would usually implement it as a boolean, but I like it this way. It’s trickier, but it cleans up a lot of potential if statements. Neat!

Now we are back to animate in all the various numbers, if they need animating. Again we iterate over the digits in each span, and then apply a really cool custom animation on them if they have changed.

The animation takes advantage of hidden overflow in the CSS to animate the digit down and thus out of view, then moves it up above the visible area and animates in back down and into view again. It’s a great combination of CSS and jQuery for a nice effect.

Since the bulk of this is stuff we’ve seen, I’ll just let show the code (though I am curious what’s going on in that “Messy” comment, crazy chaining!

Lastly we declare and kick off the timer for the count down. I would probably have moved this up, it’s a bit weird to see timer on line 151 before it’s declared. It’s a little thing, and just my preference.


So that was neat!

Since I found a bug Drew has fixed that and went back and tweaked the code a bit more. Most notably he pulled out and boiled down the countdown animation into this function.

This is a really great effect, I can’t emphasize how cool it looks.

Reading another persons code exposed a few things about my own coding style that I wasn’t conscious of. What surprised me most is that I wasn’t bothered by any formatting issues. I’m rather opinionated on formatting, for instance I claim to despise cuddled else’s (no newline between a closing curly brace and an else), but Drew does that and I breezed right over them.

It was also interesting to see a totally different approach to this problem. I implemented a countdown in the middle of last year, but it was day only and not JavaScript. My natural approach would be handling time pieces as plain integers, so it was cool and kind of mind bending to see this approach of partitioning digits into arrays.

I think I will try to make a habit of this process, and I like the brain dump while reading, I think it helped it stick better to express it in writing while fresh in my mind.

Does anyone have any suggestions for what to read next? A favorite piece of code? Preferably something I can do in one sitting.

Naive Search with JavaScript

February 2, 2012 » Geek

On a recent project I had the need to implement a basic search functionality into a web interface. This isn’t unusual, but what was different is that the data in this project was fairly static, and was kept in JSON on disk (and cached into memory). Additionally, there would be a point where it was moved off of our servers, onto an entirely different stack (hence the JSON).

There was minimal server side processing so far, and I did not want to add more overhead that would need to be ported. So, I decided to implement my search in JavaScript (with some help from Python). My idea was to do very basic string matching on a pre-built index. In this article I am going to lay out my implementation, but on a dummy data set.

The Process

This search breaks down into three steps:

  1. Build Search Index
  2. Perform Search
  3. Connect To Interface

Before we start writing that, let’s cover the data.

The Data

Here is the data I will be sifting through. To keep it simple, I’m just searching through some sentences with associated ID’s. It’s short and simple, but with some tweaks you can apply this to bigger data sets, as I did.

My data set will be represented in JSON for portability and easy interpretation from JavaScript.

data.json (92278f)

The Index

To facilitate easy matching, I’m going to build a search index that will be a dictionary, with individual words (tokens) as the keys, and arrays of ID’s as the values.

I’ve decided on Python for my index builder. Handling JSON from Python is easy, though if you have a version older than 2.6 you will need to use a different import, such as simplejson.

The core of this functionality is the tokenizer. To build this, we need to determine our rules. Since this is a simple search, I’m going to tokenize on word boundaries, it will be case insensitive, and I will only accept the characters A-Z, single quote and dash inside of a word.

Here is my implementation of the tokenizer, that follows these rules:

build_index.py (92278f)

The remainder of the Python is simply opening and parsing the JSON.

build_index.py (92278f)

Run that, and we get the dictionary we wanted:

output.txt (92278f)


Now that we have an index to work with, let’s convert it to JSON. This just takes a little tweak to the Python.

build_index.py (89ba77 )

That gives us a JSON file to work with.

index.json (89ba77)

Now we’re going to load that JSON with an AJAX call, so we have the index to work with.

search.js (89ba77)

Once we have that data, finding matches is just a matter of looking them up in Search.index. Below I’ve used a loop that will search through an array of terms, and then accumulate the matches.

search.js (89ba77)

It works!
It works!

Hook It Up

Just a little bit remains to connect this thing. First we need to port over the tokenizer from Python to get a consistent result. Pretty easy port.

search.js (216a15)

JavaScript tokenize in action.

Last we just need to apply our functions to some inputs, which we hook up with some jQuery.

index.html (216a15)

Hooked Up

Make It Better

This is not, by any means, a complete system. You would want to grab the results and match up the ID’s to a more useful output. Additionally, you could drop the AJAX call and use a script tag to bring in the index.

There are plenty of improvements you can make, and I’d love to know if you make them!

For reference, here is the complete source: https://gist.github.com/1673557.