1 var ArrayIndex = require('./')
2 var inherits = require('util').inherits
3 var assert = require('assert')
10 function Arrayish (length) {
11 ArrayIndex.call(this, length)
12 this.sets = Object.create(null)
15 // inherit from `ArrayIndex`
16 inherits(Arrayish, ArrayIndex)
19 // create an instance and run some tests
20 var a = new Arrayish(11)
21 assert.equal(a.length, 11);
23 assert.throws(function () {
25 }, /you must implement the `ArrayIndex.get` Symbol/)
27 assert.throws(function () {
29 }, /you must implement the `ArrayIndex.set` Symbol/)
33 * This "getter" function checks if the index has previosly been "set", and if so
34 * returns the index * the value previously set. If the index hasn't been set,
35 * return the index as-is.
38 Arrayish.prototype[ArrayIndex.get] = function get (index) {
39 if (index in this.sets) {
40 return +this.sets[index] * index
47 * Store the last value set for this index.
50 Arrayish.prototype[ArrayIndex.set] = function set (index, value) {
51 this.sets[index] = value
55 // test getters without being "set"
62 // test setters, followed by getters
64 assert.equal(10, a[10])
66 assert.equal(20, a[10])
68 assert.equal(30, a[10])
71 assert.equal(11, a.length)
75 var b = [0, 1, 2, 3, 80, 5, 33.325919999999996, 7, 8, 9, 30]
76 assert.equal(JSON.stringify(b), JSON.stringify(a))
80 * It should work when invoking as a Mixin.
84 ArrayIndex.call(this, 5);
88 // these throw because there's no __get__ and __set__ function defined
89 assert.throws(function () {
92 assert.throws(function () {
96 f[ArrayIndex.get] = function (index) {
100 assert.equal(f[0], 0);
101 assert.equal(f[1], 2);
102 assert.equal(f[2], 4);
103 assert.equal(f[3], 6);
105 f[ArrayIndex.set] = function (index, value) {
106 this['foo' + index] = value;
110 assert.equal(f.foo1, 'bar');