Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

add toArray(), toJSON, and toString() functions

  • Loading branch information...
commit 164f8f49f5cd209704077ab0afe2903bd45b5513 1 parent 5416d4f
@TooTallNate authored
Showing with 40 additions and 0 deletions.
  1. +35 −0 index.js
  2. +5 −0 test.js
View
35 index.js
@@ -52,6 +52,41 @@ ArrayIndex.prototype.__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.
*/
View
5 test.js
@@ -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))
Please sign in to comment.
Something went wrong with that request. Please try again.