## 30 May, 2009

### Coord constructor.

In an earlier post, I mentioned that I never had need for a genuine hash. Although that is still technically correct, I did end up using bits and pieces of the `Hash` constructor to create a `Coord` constructor.

Here's how you create it:

```// Infinite constraints:
var coord = new Coord();

// Set constraints:
var coord = new Coord({
top: 0,
right: 50,
bottom: 50,
left: 0
});

// Unset constraints become infinite:
var coord = new Coord({
right: 50,
bottom: 50
});
```

Using the coordinate system itself is easy. You use the `pt()` method to get the value of a point:

```// Get the value of point (0,10):
coord.pt(0, 10);
```

To set or delete a point, you use the chained method `set()`:

```// Set the value of (0,10) to the value 5:
coord.pt(0, 10).set(5);

// Delete the point (0,10):
coord.pt(0, 10).set();

// You can also delete like this:
coord.pt(0, 10).set(null);
```

By default, it has infinite constraints: you can create a new point anywhere in the coordinate system. However, if you set constraints and then try to create a new point that is outside of the constraints, it will not create the point. I use CSS syntax for familiarity.

As an example:

```var coord = new Coord();
// coord.pt(-1, -1).set(1) == 1
// coord.pt(11, 11).set(1) == 1
```
```var coord = new Coord({
right: 10,
bottom: 10
});
// coord.pt(-1, -1).set(1) == 1
// coord.pt(11, 11).set(1) == undefined
```
```var coord = new Coord({
top: 0,
right: 10,
bottom: 10,
left: 0
});
// coord.pt(-1, -1).set(1) == undefined
// coord.pt(11, 11).set(1) == undefined
```

Using this system, you can guarantee that every point will lie within a certain range. It accepts both positive and negative numbers.

You cannot change the size of the system after it has been created. However, you can obtain the size with the `size()` method; which returns an object with the size properties:

```var coord = new Coord({
top: 0,
right: 50,
bottom: 50,
left: 0
});
var size = coord.size();
// size.top    == 0
// size.right  == 50
// size.bottom == 50
// size.left   == 0
```

The coordinate system also provides a `length` property, that lists how many points are currently in the system. You can also use the `forEach()` method to iterate over each point:

```coord.forEach(function (x, y, value) {
alert("(" + x + "," + y + ") has the value: " + value);
this.pt(x, y).set(10);
});
```

Note how the function is given the x, y, and value of each point. In addition, `this` is set to the current executing coordinate system, making it easy to use the `pt()` method.

You can use this to implement a Cartesian coordinate system, or augment the DOM; for instance allowing collision-detection in JavaScript.