Skip to content

Instantly share code, notes, and snippets.

@WebReflection
Created November 30, 2011 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save WebReflection/1410420 to your computer and use it in GitHub Desktop.
Save WebReflection/1410420 to your computer and use it in GitHub Desktop.
Array extras applied to Objects
(function (Object) {
// (C) WebReflection - Mit Style License
// @wtf? Array extras applied to Objects
function OPmap(key, i, arr) {
this.n[key] = invoke(this, key);
}
function OPfilter(key, i, arr) {
invoke(this, key) && (this.n[key] = this.s[key]);
}
function define(key, callback) {
defineProperty(OP, key, {value: callback});
}
function generic(key, i, arr) {
return invoke(this, key);
}
function invoke(self, key) {
return self.f.call(self.c, self.s[key], key, self.s);
}
function iterator(self, callback, context, freshlyBaked) {
return {s: self, f: callback, c: context, n: freshlyBaked};
}
var
EVERY = "every",
FOR_EACH = "forEach",
MAP = "map",
SOME = "some",
OP = Object.prototype,
defineProperty = Object.defineProperty,
keys = Object.keys
;
if (FOR_EACH in OP) return;
define(EVERY, function every(callback, context) {
return keys(this)[EVERY](
generic,
iterator(this, callback, context)
);
});
define("filter", function filter(callback, context) {
keys(this)[FOR_EACH](
OPfilter,
iterator(this, callback, context, context = {})
);
return context;
});
define(FOR_EACH, function forEach(callback, context) {
keys(this)[FOR_EACH](
generic,
iterator(this, callback, context)
);
});
define(MAP, function map(callback, context) {
keys(this)[MAP](
OPmap,
iterator(this, callback, context, context = {})
);
return context;
});
define(SOME, function some(callback, context) {
return keys(this)[SOME](
generic,
iterator(this, callback, context)
);
});
}(Object));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment