Posts tagged with Javascript

regexInArray

September 8th, 2010

Javascript arrays have an inArray() method that tests for the existence of a search object and returns its key. However, sometimes you don’t want to test for an exact match. I wrote a little function that will test a regex instead. Like inArray() it returns -1 if none of the elements satisfy the condition.

function regexInArray(search, arr) {
  for (var k = 0; k < arr.length; k++) {
    if (search.test(arr[k])) {
      return k;
    }
  }
  return -1;
}

MathPlus

September 8th, 2010

I’ve been slowly assembling a set of common mathematical functions in a Javascript library called MathPlus. Tonight I added support for vectors. Check it out and let me know what you think.

Imajs

July 23rd, 2010

I made this a month or two ago but I forgot to mention it here: Jacob Biljnai of Tumblr was complaining on Twitter that there wasn’t a Javascript-based image resizing API so I made him one using App English, Imajs. Enjoy.

HTML5 Video Transformation

June 4th, 2010

This week I’ve been messing around with the HTML5 video element and have discovered you can do some pretty cool stuff. For instance, Mozilla shows how to do greenscreen image replacement while a video is played. This is very cool but there’s an annoying intermediate step required: since you cannot directly fetch raw frame image data from a video element, you must write each frame to an intermediate canvas element and then use its getImageData method to get raw image data you then transform and write to the final canvas element.

I brought this up in an email to the HTML5 Doctors last night. Remy suggested that I write up a blog post with some benchmarks, so here are some quick findings. You can find my code on GitHub. In the example I take a video and invert all its colors, frame-by-frame.

Here’s my html:

And my Javascript:

Using Chrome 5.0.375.55 on OS X and its developer tools, I took a heap snapshot after loading benchmark.html. There were 2171 code (what, I don’t know) and 12463 objects, taking up 464.70 kb and 866.97 kb respectively. I then started the profiler and executed the following Javascript: var video = document.getElementById("video); video.play();. Once the video appeared to have stopped (confirmed by video.ended) I stopped the profiler and took another heap snapshot. This time there were 2202 code and 13037 objects taking up 471.58 kb and 922.11 kb. Not surprisingly the profile shows that processFrame() takes up the vast majority of execution time (77.63% self, 83.65% total).

This all leads me to believe that, at least for smaller videos like the 480 x 280 px video I used from Apple’s documentation, there are not significant performance issues when transforming videos frame-by-frame in Javascript.

That being said, I still find the process ineffiecent and would like to be able to get a sort of FrameData object directly from video elements, just like you can get an ImageData object from canvas elements. This would mean I would only need to use one canvas element (canvas2 in my example), instead of two.

Javascript Type Gotchas

May 1st, 2010
typeof null // -> object
null instanceof null // -> TypeError: Can't use instanceof on a non-object.
true instanceof Boolean // -> false
true == new Boolean(true) // -> true
true === new Boolean(true) // -> false

Needless to say, this is very annoying if you’re trying to be be careful with your types and just goes to show that not everything is an object in Javascript. Come back soon for my attempt at a solution.

You got pointers in my Javascript!

April 8th, 2010

Why yes, yes I did! Introducing pointy.js. Pointers, trees, circular linked lists, they’re all there. It’s been a decade since I used pointers in C++, so please bear with me if there are problems. Gentle corrections welcome!

Aggregation Strategies

March 3rd, 2010

How do you find the minimum, maximum, and average of values of a set of samples over time? What if some of your data sources are unreliable and prone to drop in and out? Should you group them into regular buckets, even if that may mean multiple samples from source A and none from source B? Or should you calculate instantaneous aggregate numbers whenever a new sample comes in at the expense of having as many aggregate points as samples and potentially unevenly distributed across time? Are there better ways?

In the end I hacked up a simple library, aggregate.js, to test various strategies using Node. Right now I just have the two basic windowing and instantaneous strategies implemented, but I plan on adding more as needed.

Javascript Constructors with an Array of Parameters

March 3rd, 2010

Say we have:

function myObj() {
  this.input = Array.prototype.slice.call(arguments);
}

We can pass a variable or an array but :

var myObj1 = new myObj(1);
myObj1.input // -> [1]
var myArr = [1, 2, 3];
var myObj2 = new myObj(myArr);
myObj2.input // -> [[1, 2, 3]]

How then can we get, while still using myArr:

myObj3.input // -> [1, 2, 3]

Here’s how, courtesy of this site:

var myObj3 = new myObj();
myObj.prototype.constructor.apply(myObj3, myArr);

Note that myObj3 needn’t be an instance of myObj, it just needs to be an existing value so that the global object isn’t used as the value of this.

This is pretty cool, though of course you can do it much easier in languages such as Scala:

val myObj4 = new myObj(myArr: _*)

Javascript Primitives

February 13th, 2010

From the Mozilla Javascript Glossary:

primitive, primitive value
A data that is not an object and does not have any methods. JavaScript has 5 primitive datatypes: string, number, boolean, null, undefined. With the exception of null and undefined, all primitives values have object equivalents which wrap around the primitive values, e.g. a String object wraps around a string primitive. All primitives are immutable.

Did you know that all Javascript primatives are immutable? I sure didn’t.

My latest Scala-inspired Javascript library: pf.js

February 4th, 2010

What is a function? While many use the words ‘method’ and ‘function’ interchangeably, more mathematically-inclined programmers make a distinction between functions and methods based on between you are guaranteed a return value. Scala is one programming language that makes a distinction between functions and methods (though it’s actually pretty easy to jump between the two). Great, just like plenty of other languages, nothing special here. Javascript functions are funny beasts. On one hand, they seem to be simple subroutines which can be passed arguments and can enclose variables – pretty standard methods in other words. However, regardless of whether you include return statements in a function, something is actually returned, undefined being returned if you hadn’t specified a return value. Hmm, so they’re kind of like mathematical methods except there’s no way to know without looking at a function’s source code whether the author failed to return a value for the input you gave it or actually did return something, the undefined object.

However, Scala also provides a middle ground with PartialFunctions. PartialFunctions are cool because they are only defined for specific inputs and you can check this. In addition, because they are defined for specific inputs, you can combine several PartialFunctions to create a new PartialFunction which is defined for the union of all the original PartialFunctions’ inputs. Wouldn’t it be cool if Javascript did that too? Well, now it can with pf.js. Enjoy.