sirisian / ecmascript-types

ECMAScript Optional Static Typing Proposal http://sirisian.github.io/ecmascript-types/
453 stars 4 forks source link

Jagged and multidimensional support via custom indexing support for arrays. #12

Closed sirisian closed 7 years ago

sirisian commented 7 years ago

Introduce a syntax for defining custom indexing operators on typed arrays. To index a grid of data one uses y * width + x. Typing this every time one is indexing an array can be tedious and error prone if one wants to change the data structure indexing.

Refer to this extra issue for more syntax to consider: https://github.com/sirisian/ecmascript-types/issues/10

Along with normal array allocation with

let grid = new uint8[16];

the user can define a length type:

let grid = new uint8[16:uint32];

Now defining an index operator would require extra syntax like:

let grid = new uint8[16:uint32, (x:uint32, y:uint32) => y * 4 + x];
// grid[0] // type error, expected two arguments
grid[2, 1] = 10;

This adds an optional lambda that would ideally be inlined by the implementation. Rather defining jagged or multidimensional arrays separately with their own syntax we instead create this index overload to define what it is. By default (i) => i would be the index operator.

Refer to: https://github.com/sirisian/ecmascript-types/issues/11

That issue explains views on typed arrays. It doesn't yet define a syntax, but we can use the basics used for normal TypedArray types. Say you wanted to index an array in a few ways then you'd simply use the syntax:

var gridView = new uint8[(x, y, z) => z * 4 * 4 + y * 4 + x](grid.buffer);
sirisian commented 7 years ago

I've added this to the proposal.

doodadjs commented 7 years ago

I'm not sure to understand the lambda.... Could not been :

var gridView = new uint8[16, 4, 1]()
sirisian commented 7 years ago

Possibly, but it hardcodes the lambda function into one convention. The idea of the lambdas is that one could have any indexing function. I just included the standard x,y,z indexing operator. Say someone had a different convention though where they needed to index along z frequently. Using the one I defined:

for (var z = 0; z < 4; ++z)
{
    // do something with gridView[0, 0, z]
}

This would invariably lead to bad cache locality. Someone programming would be forced, due to language conventions, to do gridView[z, y, x] which would be annoying. With the lambda syntax the programmer can transparently change the data structure by editing the index operator and increase readability.