Showing posts with label TypeScript. Show all posts
Showing posts with label TypeScript. Show all posts

15 February 2013

JSEN: JavaScript Expression Notation

That idea I was talking about yesterday? Storing mathematical expressions as JSON? I went ahead and made it as a TypeScript project and released it on GitHub:


JavaScript Expression Notation (JSEN)



Still need to complete the unit test coverage and add a couple more features. I made a change from my original post to the syntax for namespace references. (The reason? I realized I needed to be able to use "*" as a local identifier for multiplication.) They work within Namespace declaration blocks, but I need to make them work at the higher level of Namespaces declaration blocks as well. (Done.) I also want to allow functions to be used as namespaces. (Done.)

This is possible right now:

jsen.decl('my-fake-namespace', {
   'js': 'http://ecma-international.org/ecma-262/5.1',

   'x': 10,
   'y': ['js:Array', 1, 2, 3],
   'z': ['js:[]', 'y', 1]
});

jsen.eval('my-fake-namespace', 'x'); // 10
jsen.eval('my-fake-namespace', 'y'); // [1, 2, 3]
jsen.eval('my-fake-namespace', 'z'); // 2

jsen.expr('my-fake-namespace', 'x'); // 10 // Deprecated
jsen.expr('my-fake-namespace', 'y'); // Deprecated
    // ["http://ecma-international.org/ecma-262/5.1:Array", 1, 2, 3]
jsen.expr('my-fake-namespace', 'z'); // Deprecated
    // ["http://ecma-international.org/ecma-262/5.1:[]", "y", 1]

Eventually something like this will be possible as well:

28 January 2013

Using TypeScript to Define JSON Data

JSON has gradually been wearing away at XML's position as the primary format for data communication on the Web. In some ways, that's a good thing: JSON is much more compact and readable. In other ways, it's not so great: JSON lacks some of XML's features.

One of these features is document type definitions. For XML, there are a variety of formats (DTD, XML Schema, RELAX NG, etc.) for specifying exactly what your XML data looks like: what are the tag names, possible attributes, etc. JSON is a lot more loosey-goosey here.

Okay, that's not entirely true: there is JSON Schema. I've never known anyone to use it, but it's there. It's awfully verbose, though. (So are the definitional formats for XML, but it's XML  you expect it!)

I was thinking about this the other day, and I realized that there is actually a great definitional format for JSON already in existence: TypeScript! If you haven't heard of it, TypeScript is a superset of JavaScript which introduces optional strict typing. And since JSON is a subset of JavaScript, TypeScript is applicable to JSON as well.

One of the great features of TypeScript is that interface implementation is implicit. In Java or ActionScript, you have to specifically say that a type "implements MyInterface". In TypeScript, if it fits, it fits. For example:

interface List
{
    length: number;
}

function isEmpty(list: List): bool
{
    return list.length === 0;
}

console.log(isEmpty("")); // true
console.log(isEmpty("foo")); // false
console.log(isEmpty({ length: 0 })); // true
console.log(isEmpty({ length: 3 })); // false
console.log(isEmpty({ size: 1})); // Compiler error!

(Note: for some reason that I can't fathom, isEmpty() doesn't work on arrays. Well, TypeScript is still in development  version 0.8.2 right now. Update: I filed this as a bug.)

Note that you can use interfaces even on plain objects. So of course you can use it to describe a JSON format. Here's an example from a project I hope to release before too long:

interface Model
{
    uid: string;
}

interface Name extends Model
{
    citationStart?: number;
    html?: string;
    namebankID?: string;
    root?: bool;
    string?: string;
    type?: string;
    uri?: string;
    votes?: number;
}

interface Taxon
{
    canonicalName?: Name;
    illustrated?: bool;
    names?: Name[];
}

Now, for example, I can declare that an API search method will return data as an array of Taxon objects (Taxon[]). And look how compact and readable it is!

Note that there is one drawback here: there is no way to enforce this at run-time. JSON Schema might be a better choice if that's what you need. But for compile-time checking and documentation, it's a pretty great tool.

09 December 2012

Introducing Pictish, an image-processing library for web browsers

Boy, between RaphaëlTS, SHA-1, and Haeckel, I've been releasing an awful lot of TypeScript/JavaScript libraries lately, haven't I? Anyway, here's another!


Pictish takes advantage of canvas elements and Typed Arrays to provide fast routines for processing raster image data. Here is a rundown of the currently available functions:
  • createImageData()
  • fromFile()
  • fromHTMLImage()
  • crop()
  • flipX()
  • flipY()
  • scaleDown()
  • quarter()
  • silhouettize()
All of these functions have been tested and optimized. More information is available in the documentation at the BitBucket site. Note that since canvas elements and Typed Arrays are based on more recent specifications, not all browsers support it. (For what it's worth, I've been testing in Chrome.)

(The sharp-eyed may notice that last function and wonder if it might have something to do with another project of mine. The answer is yes.)

Next planned step is to create a PNG file encoder  that could take a while, though.

08 December 2012

SHA-1 with Typed Arrays

There are already SHA-1 implementations for JavaScript, but all the ones I found use strings as input. This is fine for generating hashes from small amounts of data, but not so great for large binary files. So I've created a SHA-1 library that optionally accepts ArrayBuffer objects.


Note that this will not work on browsers that do not support Typed Arrays.

I ran some tests and found that in Chrome it takes less than half a second to hash 10Mb of data.

Hope someone finds this useful! (At the very least, I will.)

02 December 2012

Haeckel: A Code Library for Browser-Based Evolutionary Diagrams

For a while now I've been writing posts with diagrams like this one, showing the evolution of cranial capacity in mangani over the past seven million years:


How did I make them? Originally it was all ad-hoc ActionScript code, but more recently I've begun to organize the code into a library and translate it into TypeScript (which, in turn, is automatically translated into JavaScript). Although this library is still in progress, I've decided it's at a stage where I can open it to the general public.

This library includes functionality for:

  • Modeling scientific concepts such as taxa, phylogeny, character states, stratigraphy, and geography.
  • Processing scientific data (notably calculating morphological distance and inferring unknown character states).
  • Rendering data into charts as Scalable Vector Graphics, using RaphaëlJS.
For a while I struggled with what to call this library. It's neither purely about science nor purely about graphics. Finally I got my inspiration from RaphaëlJS, a graphics library named after a great artist. I named my library after a man who was both a great artist and a great biologist:

19 October 2012

RaphaëlJS + TypeScript = RaphaëlTS

RaphaëlJS is a library, written in JavaScript, for creating vector graphics on the web. It's commonly used because it supports all web browsers, including the good ones (which use SVG) and Internet Explorer (which uses VML). Among other things, it's the rendering engine of the ExtJS and Sencha frameworks.

TypeScript is a new web language that extends JavaScript, adding optional strict typing. This is a big improvement on JavaScript because it allows more errors to be caught at compile-time rather than at run-time (for example, if you pass a number to a function that expects an array). However it's not as obnoxious as some strictly-typed languages, because the typing is optional and often implicit.

I've spent some time recently playing around with TypeScript and my verdict: it's wonderful. I only want to use this from now on (at least for large projects). It's a great language, and, since it's an extension (or superset) of JavaScript, all existing JavaScript code works just fine in it. (This is a big advantage it has over Dart, an otherwise excellent language as well.)

But while you can just include a JavaScript library in your TypeScript projects, you don't get the full benefit of the compile-time checking (or the code-hinting) unless that library's entities have been declared. TypeScript allows for ambient declarations: defining or partially defining an entity (class, interface, method, variable, etc.) without actually creating it. As an example (and a very useful one at that), here is a TypeScript declaration file for jQuery: jQuery.d.ts

Today I wondered if anyone had made something like this for RaphaëlJS. I wasn't able to find one, so ... I made one. Here you go: https://bitbucket.org/keesey/raphaelts/src

If you're using the Visual Studio plugin or the TypeScript playground (other editors are bound to come out soon), you can now program type-safe RaphaëlJS code with auto-complete (=IntelliSense).

I've verified that it compiles, but I haven't fully tested it—if anyone experiences issues please let me know. (Or feel free to fork the project).

Hope someone else finds it useful ... I know I will!