Voronoi diagram in JavaScript

Datetime:2016-08-23 02:52:37         Topic: JavaScript  ActionScript          Share        Original >>
Here to See The Original Article!!!

I always wanted to try programming in JavaScript, so I decided to rewrite my implementation of Fortune's algorithm from C++ and ActionScript 3 into JavaScript.

What is interesting about JS

Up until now, I knew that JS is very similar to ActionScript and that it doesn't have classes and data types. It sounds a little weird, but it's true JS is object-oriented language, just like C++ or AS3 are, but there are no classes and data types. Instead of it, Prototype-based programming is used . It is a little hard to get used to it, but after some time it doesn't mind you, or even more, you start to like it

Rewriting AS3 into JS

I started my learning with an article on Wikipedia . To get some practice with JS, I decided to rewrite my library for generating Voronoi diagrams, which I already had written in AS3 and C++, into JavaScript. I was a little worried, that it will be too hard, but finally it was pretty easy, and what's more, it really worked! I had finished in about an hour.

The result

You can see the result above. I draw diagrams into HTML element "canvas". Unfortunatelly, I didn't have an implementation of a heap or priority queue in JS, so i used a classic array. Thus, asymptotic time complexity is $O(n^2)$ instead of $O(n * log(n))$, which AS3 and C++ versions have.

When you rewrite a common object-oriented imperative language into JS, it can be summarized into few steps:

  • Remove type specification in variable and function definitions
    • int a = 5; var a:int = 5; => var a = 5;
  • Rewrite the definitions of classes into function definitions. When you call this function with a "new" keyword, it works as a constructor.
  • Attach all class' methods to it's prototype.


Put your ads here, just $200 per month.