Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
TooTallNate committed May 25, 2012
0 parents commit 7a27eda
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
@@ -0,0 +1 @@
node_modules
60 changes: 60 additions & 0 deletions index.js
@@ -0,0 +1,60 @@

/**
* Module dependencies.
*/

var debug = require('debug')('array-index')

/**
* Here's a pure JS implementation.
* A harmony proxy impl could help.
*/

var e = module.exports = {}

e.__ensureLength__ = function ensureLength (_length) {
var length = _length | 0
var cur = e.__length__ | 0
var num = length - cur
if (num > 0) {
var desc = {}
debug('creating a descriptor object with %d entries', num)
for (var i = cur; i < length; i++) {
desc[i] = setup(i)
}
debug('done creating descriptor object')
debug('calling Object.defineProperties() with %d entries', num)
Object.defineProperties(e, desc);
debug('finished Object.defineProperties()')
e.__length__ = length
}
}

e.__get__ = function () {
throw new Error('you have to implement the __get__ function')
}

e.__set__ = function () {
throw new Error('you have to implement the __set__ function')
}

function setup (index) {
function get () {
return this.__get__(index)
}
function set (v) {
return this.__set__(index, v)
}
return {
enumerable: true
, configurable: true
, get: get
, set: set
}
}

// just define the 100,000 entries for you.
// takes like 450ms on my comp :\
debug('defining the first 100,000 entries')
e.__ensureLength__(100 * 1000)
debug('DONE defining the first 100,000 entries!')
21 changes: 21 additions & 0 deletions package.json
@@ -0,0 +1,21 @@
{ "name": "array-index"
, "description": "Invoke getter/setter functions on array-like objects"
, "keywords": [
"index"
, "array"
, "getter"
, "setter"
, "proxy"
]
, "version": "0.0.0"
, "author": "Nathan Rajlich <nathan@tootallnate.net> (http://tootallnate.net)"
, "repository": { "type": "git", "url": "git://github.com/TooTallNate/array-index.git" }
, "main": "./index.js"
, "scripts": {
"test": "mocha -gc --reporter spec"
}
, "dependencies": {
"debug": "*"
}
, "engines": { "node": "*" }
}
22 changes: 22 additions & 0 deletions test.js
@@ -0,0 +1,22 @@

var ArrayIndex = require('./')


/**
* Create a "subclass".
*/

function Arrayish (length) {
ArrayIndex.__ensureLength__(length)
}

// inherit from `ArrayIndex`
Arrayish.prototype = Object.create(ArrayIndex)

// define the index getter function
Arrayish.prototype.__get__ = function get (index) {
console.error('invoking indexed getter: %d!', index)
return index
}

module.exports = Arrayish

0 comments on commit 7a27eda

Please sign in to comment.