Permalink
Browse files

initial commit

  • Loading branch information...
0 parents commit 7a27eda4b87e8242c311541db31c545c4fc4aef6 @TooTallNate committed May 25, 2012
Showing with 104 additions and 0 deletions.
  1. +1 −0 .gitignore
  2. +60 −0 index.js
  3. +21 −0 package.json
  4. +22 −0 test.js
1 .gitignore
@@ -0,0 +1 @@
+node_modules
60 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 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 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.