Posts about javascript

Python-Style OO in Javascript

A while a go I wrote a post on Prototype Inheritence in Python. This time, I am somewhat going the opposite direction. That's right: Python-Style OO in Javascript.

Now, I don't think I am the first one who thought of this. In fact, Prototype.js does something like this for their method extensions to DOM objects. The main idea is this: if you specify self as the first argument to a method explicitly, you will be able to use self inside of nested closures within the method without having to create a self variable manually, i.e.:
var self = this
or doing something like Prototype's bind, or pass the context explicitly around like the Array methods forEach, map, every, etc.

This is but a small proof-of-concept. The result is you can write a class like this:
var Man = Class(Object)({
  __init__: function(self, name){
    self.name = name
  },
  greeting: function(self, other){
    setTimeout(function(){
      self.say("Hello, " + other.name + ", my name is " + self.name)
    }, 100)
  },
  say: function(self, msg){
    sys.puts(msg)
  }
})
Take it for a spin:
var dan = new Man('Dan')
var john = new Man('John')
dan.greeting(john)
john.say('How do?')
Output:
How do?
Hello, John, my name is Dan
The implementation of Class looks like this:
function toArray(args){
  var ret = []
  for (var i = 0; i < args.length; i++)
    ret.push(args[i])
  return ret
}

function Class(parent){
  function bind(func, obj){
    var ret = function(){
      var args = toArray(arguments)
      args.splice(0, 0, obj)
      return func.apply(undefined, args)
    }
    return ret
  }
  
  return function(attrs){
    return function(){
      for (var name in attrs){
        var value = attrs[name]
        if (typeof(value) == 'function'){
          this[name] = bind(value, this)
          this[name].name = name
        }else{
          this[name] = value
        }
      }
      this.__init__.apply(this, arguments)
    }
  }
}
Full source can be found here. I ran it in node. This could be an interesting approach to avoiding "this-hell".

Posted by Toby 2 months ago about javascript, programming and python (0 comments)

Quick And Dirty JSONP

I needed JSONP for WordyClouds, and since I am trying not to have to use jQuery, I just rolled my own. JSONP is a simple hack, so this is but a short little snippet:
var JSONP = {}
JSONP.get = function(url, callback){
    var scriptTag = document.createElement('script')
    var callbackName = '_' + new Date().getTime()
    JSONP[callbackName] = function(){
        callback.apply(null, arguments)
        delete JSONP[callbackName]
        document.head.removeChild(scriptTag)
    }
    if (url.indexOf('?') != -1)
        url += '&callback=JSONP.' + callbackName
    else
        url += '?callback=JSONP.' + callbackName
    scriptTag.src = url
    document.head.appendChild(scriptTag)
}
Example usage:
JSONP.get('http://feeds.delicious.com/feeds/json/tags/your_username', function(data){
    // Woohoo! You got data!
})

Posted by Toby 2 months ago about javascript and programming (0 comments)

WordyClouds - I am Coming After Wordle

After playing around a bit with create word clouds I've decided to write an HTML 5 version of Wordle.net. I am calling it WordyClouds. I've started the beginnings of the code on github.

Also, here's the updated bookmarklet <-- drag to toolbar to install. It does a uniformly randomized algorithm rather than Wordle's advanced packing algorithm.

As for that algorithm, I've done some research to how I might implement something close to Wordle's algorithm. I need to be able to make the best use of space - e.g. allowing tiny words to go inside of the holes inside larger letters. To do that I need the actual shape representation of all of the characters for a given font. After looking at the Canvas api, typeface.js and some cursory research into SVG, I've settled - for now - on using Canvas's bitmap feature: I would render each character required for the word cloud on a temporary scratch-pad-canvas, and then read its bitmap representation via the Canvas interface. A prove-of-concept was done and the code is here: glyphshapes.js.

Obviously, still big challenges lie ahead. How will the algorithm work? I am not exactly sure.

Update: I have written a naive non-overlapping algorithm. Here's the new bookmarklet <-- drag to toolbar to install.

Update 2: Added vertical word placement: new bookmarklet <-- drag to toolbar to install.

Posted by Toby 2 months ago about javascript and programming (0 comments)

Word Cloud Bookmarklet

Inspired by Wordle.net, I wrote a bookmarklet that generates a word cloud based on the text of the page you are on. Here it is: WordCloud <- (drag to your toolbar to install). The uncompressed source is as follows:

function getText(elm, excludeTags){
	if (elm.nodeType == 3) return elm.nodeValue;
	if (excludeTags && elm.tagName && excludeTags.indexOf(elm.tagName.toLowerCase()) != -1) return '';
	var ret = '';
	for (var i = 0; i < elm.childNodes.length; i++){
		ret += getText(elm.childNodes[i], excludeTags);
	}
	return ret;
}

function keys(obj){
    var ret = [];
    for (var key in obj) ret.push(key);
    return ret;
}

var text = getText(document.body, ['script']);
var commonWords = ['a', 'the', 'and', 'of', 'is', 'in', 'this', 'it', 'to'];
var words = text.replace(/[^a-zA-Z]/g, ' ').split(' ').filter(function(p){return p != ''});
words = words.filter(function(word){
	return commonWords.indexOf(word) == -1;
});
var freq = {};
words.forEach(function(word){ 
    freq[word] = (freq[word] || 0) + 1;
});

var markup = keys(freq).map(function(word){
	return '<span style="font-size: ' + (freq[word] / 4) + 'em">' + word + '</span>';
}).join(' ');
document.body.innerHTML = markup;

Enjoy! As a next step, I plan to use Canvas and implement more advanced layouts like the ones on Wordle.
Posted by Toby 3 months ago about javascript, programming and wordcloud (0 comments)

Continuation-Passing Style: Don't Overdo it

Continuation-Passing Style(CPS) is a style of programming that's useful for a number of use-cases, but you shouldn't get carried away and start writing all your programs in this style. Here, I am going to list 3 disadvantages of programming in this style.

Code Size

Unless your language has specific language support for writing in Continuations(e.g. Haskell), your code will have more bloat.
Example, here's a sqrt function in direct style:
function sqrt(a, b){
    return a * 2 + b * 2;
}
Here it is in CPS:
function sqrt(a, b, callback){
    multiply(a, 2, function(a2){
        multiply(b, 2, function(b2){
            add(a2, b2, callback);
        });
    });
}

Readability

The direct style is generally easier to read/understand. Take the previous sqrt example, the CPS version introduces 2 extra variable names: a2 and b2, which increases the mental load of somebody trying to read the program.

Code is Coupled to Ordering of Operations

With CPS-Style code, the order of your operation affects the structure of your code. Again, taking the sqrt example. This time, let's rewrite the direct-style version to:
function sqrt(a, b){
    var a2 = a * 2;
    var b2 = b * 2;
    return a2 * b2;
}
Here, the statements var a2 = a * 2; and var b2 = b * 2; are completely separate and independent. I could swap their order without changing the code's behavior. In the CPS-Style, the whole thing is one big statement, and therefore, to reorder the sequence of operations, it is necessary to mentally unwrap the layers of closure functions and pull out just the right ones and then put them back together. In this simple example, it wasn't actually that hard, but imagine if the code was more like this:
function sqrt(a, b, callback){
    multiply(a, 2, function(a2){
        /* code */
        multiply(b, 2, function(b2){
            /* code */
        });
        /* more code here */
    });
}
Basically, code in this style is much harder to decouple into smaller independent parts. Libraries like Do and node-promise exist to compensate for this problem, but they IMO are still a far cry from the plain ol' direct style.

The point here is that there are definite disadvantages to writing code in the Continuation-Passing Style. I am not saying that you should not use CPS, but that you should have good reasons for using it - good enough to offset its disadvantages.
Posted by Toby 3 months ago about javascript and programming (0 comments)

Convert a Function to Continuation-Passing Style

Here's a snippet that converts a normal Javascript function to its Continuation-Passing style equivalent:
function asCPS(f){
  var _f = function(){
    var callback = arguments[arguments.length - 1];
    var args = Array
      .prototype.slice
      .call(arguments, 0, arguments.length - 1)
    var retVal = f.apply(this, args)
    if (callback) callback(retVal)
  }
  _f.name = f.name
  return _f
}
So you have a normal function, say add():
function add(one, other){
  return one + other;
}
Convert it:
add = asCPS(add)
Now you can call it and get the result inside a callback, like so:
add(1, 2, function(sum){
  console.log('sum: ' + sum)
})
Posted by Toby 3 months ago about javascript and programming (0 comments)

Shape-Shifting in Javascript

Mixology is a Ruby library for what I call shape-shifting objects. 

shapeยทshifting
n. the act of changing the shape of an object's inheritance hierarchy during runtime.

It turns out that shape-shifting is incredibly easy to do in Javascript.
ClosedDoor = {
  isClosed: function(){
    return true
  },
  isOpen: function(){
    return false
  }
}

OpenDoor = {
  isClosed: function(){
    return false
  },
  isOpen: function(){
    return true
  }
}

function Door(){
  this.__proto__ = ClosedDoor
  this.open = function(){
    this.__proto__ = OpenDoor
  }
  this.close = function(){
    this.__proto__ = ClosedDoor
  }
}
Let's give it a go:
> door = new Door()
Object
> door.isClosed()
true
> door.isOpen()
false
> door.open()
> door.isOpen()
true
> door.isClosed()
false
In Javascript, "inheritance" is nothing but a link from the child to the parent: the __proto__ property. Once you have this link established, the child inherits all of the properties of the parent. You can change the __proto__ property at runtime. What the example did is simply to change the parent of the door instance to a ClosedDoor or an OpenDoor whenever the state of the door changes. This make for a nice way to implement states. +2 points for prototype inheritance!
Posted by Toby 4 months ago about javascript, programming and prototype (0 comments)

OnReady In A Smaller Package

I am sure most Javascript hackers are accustomed to the onready event. It is a pseudo-event that indicates the DOM of the pages has been loaded. document.onload is not as good as it won't fire until all the linked resources such as images are loaded as well, and if you have Javascript you want to run that can modify the appearance of the page, you would get an unwanted flicker at the beginning of the page. jQuery provides hooks to onready via $.ready(), and for prototype.js users, lowpro.js provides this via Element.onReady(). But, for hackers who don't want to use a large framework, I've created onready: the barebone implementation of the onready event. This might be useful if you want to write your own framework, or just need to write something that is very small or that has very few dependencies.

Usage:
  1. Include file:

    <script type="text/javascript" src="onready.js"></script>

  2. Use:

    OnReady(function(){ alert('DOM is now ready!'); })

Posted by Toby 5 months ago about javascript and programming (0 comments)

SuperRefresh Bookmarklet

SuperRefresh is a bookmarklet I wrote. Here is the README:

SuperRefresh Bookmarklet
========================
A bookmarklet that automatically refreshes your page as you are designing it.
Usage: 
1. Navigate to the page that you are developing in your browser - this can be either a local file or a served file.
2. Click on the bookmarklet - your page will be replaced with the 
SuperRefresh page, which will contain an iframe pointed back at your page.
3. Edit your page and save. The changes will almost immediately update within the iframe.

Click here to Try it! Bookmark it to save it for use later. Enjoy. Currently, it works for Safari, Chrome, and Firefox.

The source code is posted at GitHub.
Posted by Toby 5 months ago about bookmarklet, javascript and programming (0 comments)

How Much of the Web Actually Work Without Javascript

Recently Paul Boag showed dissatisfaction at the fact that most ecommerce sites don't work without Javascript, which stand against progress enhancement. Coincidentally, I am just now in the middle of working on a Javascript library that aims to make using CSS3 features and writing cross-browser CSS easier. So this got me thinking...

I love Javascript! I won't make any secret of this. I also love writing ajaxy web applications. Although I allow that there's value to making your site work without Javascript, to me, at least, it bares a lower priority. Of course, as is always the case, the answer depends very much on your target audience. Google Docs, for example, is more of a software tool than a web site, and so it wouldn't really make sense to make it work without Javascript - the result probably wouldn't be very useful anyway, because the essence of Google Docs, is the UI.

However, to consider the applicability of my Javascript library, I must consider whether it is acceptable to web designers that their design requires their users to have Javascript enabled.

And so, I resolved to survey how some of the major web sites and web applications look like and work like with Javascript disabled, so as to get a sense of what is the accepted norm on the web today.

The Contenders

I want to survey really popular sites. I also want to survey some content-centric sites, as well as some utility-type web-apps. The list has a Web 2.0 slant to it, but also include some old timers. Without further ado, the list is:

Scoring System

To evaluate how well each site works with Javascript disabled, I will use a scoring metric. The scoring will be based on the following 6 questions, each account for 1 point of the total score. Thus, 6 out of 6 is the perfect score.

  1. Can users navigate the site? (1 point)
  2. Can users read/view the content? (1 point)
  3. Is the site free of broken visual elements? (1 point)
  4. Can users perform the key tasks of the site? (1 point)
  5. Is the site free of broken input elements? (1 point)
  6. If things are broken, are users made aware of it? (1 point)

Let's get started!

The New York Times

Times Screenshot
As expected, the New York Times looked great. Visually it didn't look much different from a Javascript enabled version. Flash ads are replaced by static image ads. One minor hiccup is a twitter widget which appears to spin indefinitely. The video section does not work at all, and there's is no message telling you you need Javascript to run it.
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? NO
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? NO(video section)
  6. If things are broken, are users made aware of it? NO(video section)
Score 3/6 for the Times.

Digg

Digg Screenshot
Digg's page looks okay. The flash ads have disappeared, leaving whitespace in their place. You can navigate the site and view articles just fine. However, you cannot "digg" or "bury" articles, which I think is a pretty key task of the site. 
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? NO
  4. Can users perform the key tasks of the site? NO
  5. Is the site free of broken input elements? NO(digg button broken)
  6. If things are broken, are users made aware of it? NO
Digg gets a 2/6.

Facebook

Facebook Screenshot
From a visual stand point, Facebook looks perfect. You can navigate and read most of the content of Facebook, including viewing photo albums. You cannot update your status; you cannot edit your profile; you cannot record videos of yourself, and there's no warning. 
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? NO(can't update status)
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? NO
Facebook's score: 3/6.

Twitter

Twitter Screenshot
Twitter looks great without Javascript, but guess what? You cannot tweet! Bummer. You also can't edit some of the settings in your profile.
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? NO
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? NO
3/6 for Twitter.

Stack Overflow

Stack Overflow Screenshot
When you go the SO, a flash banner informs you that the site works best with Javascript enabled: nice, how refreshing! Navigation works, even asking questions, editing and posting works. However, voting does not work. For this one, I'll allow that the key tasks work, because I think the most important things are asking and answering questions; voting, although important, is secondary to those two things.
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? YES
5/6. Wow! Way to go, Jeff!

Google Search

Google Screenshot
Google Search works well, however, Image results that come up on the top of the search results show up blank. I gotta say I am very surprised that this doesn't work perfectly. I mean, this is the Google!
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? NO
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? YES
  6. If things are broken, are users made aware of it? NO
4/6 for Google Search.

CNN

CNN Screenshot
CNN worked about as well as the Times. Navigation and reading content worked but not the videos. Although the videos on CNN are more prominent than on the Times, and also break more spectacularly:
CNN Broken Video Screenshot
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? NO
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? NO
3/6 for CNN.

Amazon

Amazon Screenshot
Amazon is the one you gotta count on to do well in this. The site looks perfect. I've tested adding and update the shopping cart, which worked perfectly. I haven't actually gone all the way through and purchased something for this test, but I feel confident that everything would work.
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? YES
  6. If things are broken, are users made aware of it? N/A
6/6! Perfect for Amazon!

Ebay

Ebay Screenshot
Ebay is also an old timer ecommerce site. I don't see how it could fail any of these.
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? YES
  6. If things are broken, are users made aware of it? N/A
6/6 for Ebay.

Boagworld

BoagWorld Screenshot
Let's see if Paul puts his money where his mouth is. Boagworld looks perfect. forums work. Even the flash videos and audio work! That's pretty amazing. This is the first site I've seen where video works without Javascript.
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? YES
  6. If things are broken, are users made aware of it? N/A
6/6. Good On Ya! Paul Boag!

Google Maps

Google Maps Screenshot
Google Maps is the web application that gave life to Ajax. But much to my surprise, it actually works with Javascript turned off. Well... kinda sorta. You can plot an address on the map - even zoom and pan - but you cannot get directions. This is a tough one. On the one hand, it degrades 100% gracefully; on the other hand, without being able to give directions, it's all but crippled. 
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? NO
  5. Is the site free of broken input elements? YES
  6. If things are broken, are users made aware of it? N/A
5/6 for you, Google Maps. Hey, don't be sad, 5/6 is pretty damn good!

Google Docs

Google Docs Screenshot
Ouch! That's not a pretty picture. None of the buttons or sidebar items did anything when clicked. The loading indicators are just stuck there. This thing is pretty much...dead.
  1. Can users navigate the site? NO
  2. Can users read/view the content? NO
  3. Is the site free of broken visual elements? NO
  4. Can users perform the key tasks of the site? NO
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? NO
Wow! Our first - and possible only - 0/6. Congrats Google Docs!

Gmail

Gmail Screenshot
Two epic fails in a row from Google? Are you kidding me? Oh, but wait! What's this? On the bottom right there's a "Load basic HTML" link. You click on it and...
Gmail Screenshot 2
Tada! Talk about drama! That's like a last second Hail-Mary pass for a TD or something. The functionality is all there for the basic HTML version. The only thing I'd pick on is the fact that it's not made very apparent that this option is available. In other words, the degradation ain't so graceful. I guess you could call it clumsy degradation?
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? NO
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? YES
  6. If things are broken, are users made aware of it? NO
4/6 is all you get, Gmail!

Remember The Milk

Milk Screenshot
Well, at least they are up-front about it...
  1. Can users navigate the site? NO
  2. Can users read/view the content? NO
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? NO
  5. Is the site free of broken input elements? YES
  6. If things are broken, are users made aware of it? YES
3/6. Wow, you can not work at all, and still get 3/6!

Flickr

Flickr Screenshot
Flickr looks great, and mostly works. The things that don't work are in-place photo editing features, adding tags and people.
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? NO
4/6 for Flickr.

Picasa Web

Picasa Web Screenshot
Picasa Web informs you that your browser is not fully supported, but you are welcome to have a look around. You can see some pictures under the "Explore" tab, but not your own pictures. You also cannot upload your own pictures. It's basically crippled.
  1. Can users navigate the site? NO
  2. Can users read/view the content? NO
  3. Is the site free of broken visual elements? NO
  4. Can users perform the key tasks of the site? NO
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? YES
1/6. Google, Google. Not doing so well, are you?

YouTube

YouTube Screenshot
Hate to rub it in, but YouTube is a FAIL as well. You can still navigate the site, but not play any videos.
  1. Can users navigate the site? YES
  2. Can users read/view the content? NO
  3. Is the site free of broken visual elements? NO
  4. Can users perform the key tasks of the site? NO
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? NO
1/6 for YouTube.

WordPress

Wordpress Screenshot
WordPress works for the most part, but the parts that don't work do not degrade gracefully. Comments are broken. "Visual" editing is also broken, but you can write posts.
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? NO
4/6 for Wordpress.

GitHub

GitHub Screenshot
Last but not least, GitHub. I am, after all, the geek's geek. GitHub actually works very well. The only hiccups are small UI elements like the URL box, and the "Add File" button of the Gist dialog.
  1. Can users navigate the site? YES
  2. Can users read/view the content? YES
  3. Is the site free of broken visual elements? YES
  4. Can users perform the key tasks of the site? YES
  5. Is the site free of broken input elements? NO
  6. If things are broken, are users made aware of it? NO
4/6 for GitHub.

Final Tally

Here is a summary of all the scores:
Site vs Score Chart
The winners were Amazon, Ebay, and Boag World. 
The average score for all the sites surveyed is 3.52. Only 26% of the sites had a score of 5 or higher. What this practically means is that 74% of the sites had something broken about them when Javascript is disabled.

Summary By Metric

Summary By Metric Chart
What this chart shows is that most sites allow users to navigate and/or view the content on the site, in fact around 80% of them do. But, I think it's important to note that only 58% allowed users to perform the key tasks of the site. In other words, the other 42% are basically crippled. Another thing to note is that only 16% of sites that are broken let their users know that the site is broken without Javascript in some form or fashion - this is actually a really easy thing to fix, one could do what Stack Overflow does and just put up a flash banner on the top of the page, and be done with it. What this shows is that the developers of these sites either didn't tested the site with Javascript off, or just didn't think this was important enough to fix.

See this spreadsheet for all the data in one place.

Conclusion

What have we learned? Well, if you insist on turning off Javascript, the web isn't going to be much fun. It should be noted however that the ecommerce sites (and serious web designers) are the ones that take this very seriously.

As for the Javascript library that I am building: I plan on releasing it soon. I think maybe what I'll do is to let Javascript-enabled be the default mode of operation, but given a fallback option, albeit somewhat more complexed one.
Posted by Toby 5 months ago about javascript, programming, tech and webdesign (1 comments)

Javascript sort() Gotcha

Javascript pop quiz!

What is the result of this code?
var arr = [12, 3, 24]
arr.sort()
arr
You: [3, 12, 24]
Me: Wrong, You get an F! The correct answer is: [12, 24, 3].
You: WTF?
Me: Array.prototype.sort() uses lexical ordering by default. That is to say, it converts everything to string before comparing them. Thus, '12' comes before '24' comes before '3'.
You: So how do you make it sort numbers?
Me: You pass it a comparator function as an argument:
arr.sort(function(a, b){
  return a - b
})
You: That makes sense, I guess. But still...that is pretty messed up.


Posted by Toby 6 months ago about javascript and programming (0 comments)

Memoize for Javascript

I wrote a memoize function for Javascript today to cache file timestamps. I thought I would share it with the world. Here is the code:
function memoize(f){
    var cache = {}
    return function(){
        var keys = []
        for (var i = 0; i < arguments.length; i++){
            keys.push(typeof(arguments[i]) + ':' + String(arguments[i]))
        }
        var key = keys.join('/')
        if (key in cache){
            return cache[key]   
        }else{
            var val = f.apply(null, arguments)
            cache[key] = val
            return val
        }
    }
}
Let's say you have a function:
function f(x, y){
  return x + y * 2
}
If you memoize it:
f = memoize(f)
The first time you call f with arguments (3, 4):
f(3, 4) => 11
It will compute it, but the second time:
f(3, 4) => 11
It will merely return the cached value computed from the last time.

Note about the implementation: the equality metric used by this memoize function is: 2 objects are equal iff they are of the same type:
typeof(one) == typeof(other)
and, they have the same string represention:
String(one) == String(other)
That is it. Enjoy!
Posted by Toby 6 months ago about javascript and programming (0 comments)