Archive for the ‘javascript’ Category

2008 Programming Language Plan

Thursday, January 17th, 2008

I’ve learned a number of programming languages since I began programming 25 years ago. Earlier in my career, my choice of which programming language to learn was largely driven by external factors such as a class or job requirement, or the expectation of job demand in the future.

More recently I’ve enjoyed learning new programming languages both for the joy of learning something new, and for an increase in productivity.

While it’s true that no programming language is a silver bullet, I’ve found that the choice of programming language can provide a dramatic increase in productivity - much more so than many have asserted. The benefit can be direct, by allowing the creation of a solution to a particular problem with less time and effort than it would take using another language, or it can be an indirect by providing new ways to think about a solution.

Do you think language affects how we think?

The Past

In 1982, I spotted a Radio Shack Color Computer in a store window and immediately applied for a Radio Shack credit card which had a credit limit ($500) sufficient to purchase the computer which had 4K of RAM (I later upgraded to 16K) and no external storage (unless you count the ability to hook up a cassette recorder). Contrast the 16K RAM of that early machine with my current 2,097,152K RAM :)

That was the beginning of a life long interest in programming.

In the language list below, bold indicates a more significant professional involvement, and the year indicates when I first learned the language. I’ve also likely forgotten a few:

  1. 1982 - Radio Shack Extended Color BASIC
  2. 1983 - 6809e Assembler
  3. 1983 - Pascal
  4. 1984 - HP 48SX RPL
  5. 1984 - S/360 Assembler
  6. 1985 - COBOL
  7. 1985 - dBase III / Metafile
  8. 1985 - C
  9. 1985 - 8088/8086 Assembler
  10. 1986 - C++
  11. 1996 - Java
  12. 1997 - Perl
  13. 2002 - C#
  14. 2004 - Python
  15. 2005 - JavaScript
  16. 2006 - Ruby
  17. 2007 - PHP

The Present

Currently, I program primarily in Ruby, followed by JavaScript and the occasional PHP script. Ruby is the most productive programming language I’ve used thus far. The combination of power, pragmatism & pleasure in programming is hard to beat. If it also had performance, it would be a truly great language.

I’ve also begun learning Logo as I teach my daughter how to program. Logo is a great introduction to the Lisp family, so I hope to leverage it as I learn Scheme and Common Lisp later this year.

The Future

After completing the Logo course with my daughter, I plan on moving on to Scheme as I go through Structure and Interpretation of Computer Programs which some have called the greatest computer science text ever written.

After Scheme I plan on learning Common Lisp which has the potential to replace Ruby as my primary programming language.

Beyond Logo/Scheme/Common Lisp, the following languages are of interest:

  • Haskell
  • Erlang
  • Lua
  • ML
  • OCaml

If you know of candidates for a future programming language, feel free to add it in a comment.

You may notice that Smalltalk is lacking from the lists above. Despite its prominence in programming language history, I currently don’t feel that Smalltalk is sufficiently better/different than Ruby to warrant an investment in learning it.

After focusing on object oriented for twenty years, I have more of an interest in the functional world of programming languages (and multiple dispatch is cool :) ).

Update: I was just over at Hacker News and saw something I’ve seen many times before. In a nutshell, some guy was stating that Paul Graham’s success with ViaWeb had little to do with his choice of programming language (Lisp) and more to do with him just being a good hacker. In other words, he could’ve written it in any language. I’m so glad Paul responded because his response confirms my thoughts on the matter:

What a weird situation. I keep trying to tell people Lisp is great, and they say, no, no, you guys were just really good programmers. But if I’m such a good programmer, why don’t they believe me?

Paul Graham has written a lot on Lisp and is one of the main factors in me becoming interested in Lisp (along with the fact that Ruby pulled a lot of good ideas from it), but the simple quote above communicates volumes IMO.

Functional Features in JavaScript on Firefox

Sunday, October 7th, 2007

I was reading an article about adding code to JavaScript to make it more functional, and one of the blog commenters mentioned some built-in features that were added to JavaScript 1.6 & 1.7 on Firefox, so I checked out the links (see below) - very cool stuff.

  • Array methods

    • indexOf
    • lastIndexOf
    • every
    • filter
    • forEach
    • map
    • some
  • Array & String generics
  • Generators & Iterators
  • Array Comprehensions
  • Block Scope w/ let
  • Destructuring Assignment
  • etc.

They won’t help if you have to target IE also, but it should be possible to conditionally include your own code to implement the ones that don’t require syntactic changes for pages loaded from IE. That would reduce network load for customers using Firefox.

New in JavaScript 1.6 (Firefox 1.5)

New in JavaScript 1.7 (Firefox 2.0)

Hopefully IE will catch up someday, but if not, I can see taking advantage of Firefox specific JavaScript enhancements for niche applications. Firefox is so easy to install, that it should be easy to convince customers to use it for certain custom applications.

Logo, Ruby & JavaScript

Friday, August 31st, 2007

I’ve been teaching my eldest daughter to program in Logo over the summer. Brian Harvey has posted PDF files for a set of excellent books on learning to program in Logo on his web site. The Berkeley version of Logo he’s produced is really excellent. It’s not just your typical turtle graphics language; it has arrays, macros, file processing, graphics, etc.

While perusing his site, I came across a tiny Logo program that demonstrates a little of its power. I was curious what it would look like in Ruby, so I ported it, then I had to see what it looked like in JavaScript.

The formatting is a little messed up due to Wordpress, but each of the three choices functions is 4 lines long.

If anyone wants to add other languages, that would be great!

See the sample page for example output.

Logo

to choices :menu [:sofar []]
  if emptyp :menu [print :sofar stop]
  foreach first :menu [(choices butfirst :menu
      sentence :sofar ?)]
end
choices [[small medium large]
  [vanilla [ultra chocolate] lychee [rum raisin] ginger]
  [cone cup]]

UPDATE 9/2/07: Got an even more concise solution from Brian Harvey:

to choices :menu
   foreach crossmap "sentence :menu "print
end

Ruby

def choices menu, sofar=[]
  if menu.empty?: puts sofar.join(' ')
  else menu[0].each {|item| choices(menu[1..-1],
    sofar + [item]) } end
end
choices [['small', 'medium', 'large'],
  ['vanilla', 'ultra chocolate', 'lychee', 'rum raisin', 'ginger'],
  ['cone', 'cup']]

JavaScript

function choices(menu, sofar) {
  if (emptyp(menu)) print(sofar);
  else foreach(menu[0],
   function (x) {
    choices(menu.slice(1), sofar.concat(x)); });
}
choices([['small', 'medium', 'large'],
  ['vanilla', 'ultra chocolate', 'lychee', 'rum raisin','ginger'],
  ['cone', 'cup']], []);

I had to create a few helpers for the JavaScript version:

function emptyp(a) {
  return a.length === 0;
}
function print(list) {
  foreach(list, function (x) { document.write(x + ' '); });
  document.write('<br />');
}
function foreach(arr, f) {
  for (var idx in arr) { f(arr[idx]); }
}

UPDATE: Use <pre> </pre> tags to allow easier formatting of code. Bummer, I just discovered that Wordpress strips the <pre> tags from normal users :( I’ll go ahead and wrap code with it as they come in, so if your comment looks bad at first, it’ll be cleaned up shortly.

Greasemonkey Script for Netflix Half Star Ratings

Monday, August 27th, 2007

I wrote an article back in May about a way to give half star ratings on Netflix. It had the advantage of working in any browser and not requiring any software installation, but it wasn’t very user friendly.

Since then, I’ve been doing a lot of JavaScript coding, so I thought I’d give Greasemonkey a try. I found a script here to give half-star ratings, but I didn’t care for the hover captions and JSLint pointed out a few issues, so I cleaned it up a little:

Code

// ==UserScript==
// @name Netflix Half Stars
// @description allows half star user ratings on Netflix
// @include http://*netflix.com/*
// ==/UserScript==
// http://userscripts.org/scripts/review/8118
// Modified by Brian Adkins

if (!unsafeWindow.sbHandler) { return; }

var sbHandler = unsafeWindow.sbHandler;
sbHandler.sbOffsets = [8,18,27,37,46,56,65,75,84,94];

sbHandler.displayStrings[0.5] = ".5 stars";
sbHandler.displayStrings[1.5] = "1.5 stars";
sbHandler.displayStrings[2.5] = "2.5 stars";
sbHandler.displayStrings[3.5] = "3.5 stars";
sbHandler.displayStrings[4.5] = "4.5 stars";

sbHandler.sbImages[0.5] = new Image();
sbHandler.sbImages[0.5].src = sbHandler.imageRoot+"stars_2_5.gif";

for(var i = 2; i < 11; i++) {
sbHandler.sbImages[i/2] = new Image();
sbHandler.sbImages[i/2].src = sbHandler.imageRoot + "stars_2_" +
(Math.floor(i/2)) + (i % 2 === 0 ? "0" : "5") + ".gif";
}

sbHandler.getStarCount = function (evt) {
var x = unsafeWindow.getElementMouseCoordinate(evt, this.element);

for(var ii = 0; ii < 10; ii++) {
if(x <= this.sbOffsets[ii]) { return (ii + 1) / 2; }
}

return 0;
};

Installation

Save the JavaScript code with .user.js extension e.g. netflix_halfstar.user.js and then open that file in Firefox and Greasemonkey should prompt you to install it.

Douglas Crockford: Advanced JavaScript

Thursday, May 17th, 2007

Ok, last of the Douglas Crockford videos. These are definitely worth viewing if you program at all in JavaScript. The highlight for me was his presentation of prototypal and parasitic inheritance models and contrasting them with the pseudo-classical approach that is typically presented. I haven’t had time to analyze his approach in depth, but from a single viewing, his ideas certainly merit experimentation and seem to fit in more naturally to the JavaScript language.

I felt he did a good job of presenting natural ways of handling encapsulation, inheritance and code reuse while capitalizing on JavaScript’s strengths instead of trying to impose a class-based design onto the language. He also covered several ways of utilizing closures nicely.

function object(0) {
  function F() {}
  F.prototype = o;
  return new F();
}
newobject = object(oldobject);

var singleton = function () {
  var privateVariable;
  function privateFunction(x) {
    ...privateVariable...
  }
  return {
    firstMethod: function (a,b) {
      ...
    },
    secondMethod: function (c) {
      ...
    }
  };
}();

Object.prototype.later = function(msec, method) {
  var that = this,
      args = Array.prototype.slice.apply(arguments, [2]);
  if (typeof method === 'string') {
    method = that[method];
  }
  setTimeout(function () {
    method.apply(that, args);
  }, msec);
  return that;
};

Advanced JavaScript Part 1 of 3
Advanced JavaScript Part 2 of 3
Advanced JavaScript Part 3 of 3

Douglas Crockford: Theory of the DOM

Thursday, May 17th, 2007

Here’s a set of 3 videos by Douglas Crockford on the DOM that were in between his JavaScript and Advanced JavaScript presentations. Pretty basic material, but you may find a few helpful hints. A few comments:

  1. Comment hack for JavaScript hasn’t been necessary for 10 years!
  2. language=javascript has been deprecated
  3. type=’text/javascript’ is ignored if you use the src attribute
  4. remove any event handlers of a node before deleting it due to MS garbage collection incompetencies
  5. avoid trickling, bubbling is where the action is

Theory of the DOM Part 1 of 3

Theory of the DOM Part 2 of 3

Theory of the DOM Part 3 of 3

Douglas Crockford: JavaScript

Thursday, May 17th, 2007

Thanks to Jordan Liggitt for passing on some videos on JavaScript by Douglas Crockford who is a senior JavaScript architect at Yahoo! The first series is pretty basic, but if you’re new to the language, it’s a very good introduction. Here are some random items I thought were noteworthy:

  • Brendan Eich at Netscape originally wanted to make a dialect of Scheme, but his manager said that people wouldn’t accept “all those parentheses”, and he should make something with a friendlier syntax. Too bad, I would love to able to program Scheme in the browser
  • Brendan did sneak in lambda though, he just didn’t call it that :)
  • No separate character type, just strings of length 1
  • == and != do type coercion; === and !== do not
  • bitwise operators convert to a 32 bit signed integer and then back to a 64 bit float, so don’t use them for efficiency like you might in C
  • don’t use the with statement
  • be careful with for (var name in object) due to iteration of inherited members also
  • blocks don’t have scope, only functions do
  • vars are implicitly global if not declared
  • 4 ways to call a function

    1. functionObject(args)
    2. thisObject.methodName(args)
      thisObject[”methodName”](args)
    3. new functionObject(args)
    4. functionObject.apply(thisObject[, args])
  • don’t use eval except for trusted JSON
  • http://www.JSLint.com a tool Crockford wrote
  • Semicolon insertion: when the compiler sees an error, it attempts to replace a nearby linefeed with a semicolon and try again! Always use the full correct form including semicolon. This was a surprise to me because once I discovered semicolons were optional, I stopped using them for a cleaner look. Oops.

The JavaScript Programming Language Part 1 of 4
The JavaScript Programming Language Part 2 of 4
The JavaScript Programming Language Part 3 of 4
The JavaScript Programming Language part 4 of 4

I’ll post another entry after I go through Crockford’s advanced series.

Half star ratings on Netflix

Wednesday, May 2nd, 2007

I noticed a friend of mine (Jordan L.) who had half-star ratings (2.5, 3.5, etc.) on Netflix. When I asked him about it, he said to just “hover over the left side of the star” to get a half-star rating. This didn’t work for me, so I thought it might be a Linux vs. Windows thing and asked another friend (Mike F.) to try it out. Same result - didn’t work in IE or Firefox on Windows. Then Mike found a JavaScript file that could be installed with greasemonkey and that worked fine for him.

I’ve yet to install greasemonkey, and I don’t like the idea of installing JavaScript on my system unless I’ve thoroughly analyzed it, so I thought of another way.

I installed wireshark on my Ubuntu Linux box and sniffed the network traffic to Netflix when I rated a movie. After some experimenting and removal of extraneous info, I came up with the following URL to rate a movie with half stars. This specific URL will rate the movie “The Incredibles” with a 4.5 star rating (probably a bad example since The Incredibles clearly deserves a 5 star rating):

http://www.netflix.com/SetRating?widgetid=M70001989&value=4.5

To rate other movies, simply replace 70001989 with the id of the movie which you can find by hovering over the movie. I believe you’ll need to be logged in to Netflix already for this to work.

Now as to why Jordan can rate half-stars without the aid of a greasemonkey script, that’s still a mystery.

Update: got an email from Jordan explaining that his Netflix pages include the following two JavaScript source files:

src=”http://www.netflix.com/layout/jscript/dom_starbar_v2.js?v=126505″
src=”http://www.netflix.com/layout/jscript/dom_starbar_halfstars.js?v=126505″

I only have the first one, and from the name of the second one, I presume that’s the one that gives him the special half star rating capability. I guess Netflix favors Jordan over me :(

Update 2: mystery solved! My curiosity got the best of me so I contacted Netflix. The rep said they’re running a test and Jordan just happened to get picked (I didn’t mention Jordan, but I suppose they looked through my ‘friend’ list)! They do that periodically to test features to see if they’ll give them to the unwashed masses. I asked if they could run the test on me, and he said it didn’t work that way :) So I guess it’s the greasemonkey script or the inconvenient URL hack for the rest of us.