Skip to content

Commit

Permalink
add toArray(), toJSON, and toString() functions
Browse files Browse the repository at this point in the history
  • Loading branch information
TooTallNate committed Sep 15, 2012
1 parent 5416d4f commit 164f8f4
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
35 changes: 35 additions & 0 deletions index.js
Expand Up @@ -51,6 +51,41 @@ ArrayIndex.prototype.__set__ = function () {
throw new Error('you must implement the __set__ function')
}

/**
* Converts this array class into a real JavaScript Array. Note that this
* is a "flattened" array and your defined getters and setters won't be invoked
* when you interact with the returned Array. This function will call the
* getter on every array index of the object.
*
* @return {Array} The flattened array
* @api public
*/

ArrayIndex.prototype.toArray = function toArray () {
var i = 0, l = this.length, array = new Array(l)
for (; i < l; i++) {
array[i] = this[i]
}
return array
}

/**
* Basic support for `JSON.stringify()`.
*/

ArrayIndex.prototype.toJSON = function toJSON () {
return this.toArray()
}

/**
* toString() override. Use Array.prototype.toString().
*/

ArrayIndex.prototype.toString = function toString () {
var a = this.toArray();
return a.toString.apply(a, arguments)
}

/**
* Getter for the "length" property.
* Returns the value of the "__length" property.
Expand Down
5 changes: 5 additions & 0 deletions test.js
Expand Up @@ -69,3 +69,8 @@ assert.equal(30, a[10])

// test "length"
assert.equal(11, a.length)

a[4] = 20
a[6] = 5.55432
var b = [0, 1, 2, 3, 80, 5, 33.325919999999996, 7, 8, 9, 30]
assert.equal(JSON.stringify(b), JSON.stringify(a))

0 comments on commit 164f8f4

Please sign in to comment.