Skip to content

Instantly share code, notes, and snippets.

@nijikokun
Created February 17, 2012 04:19
Show Gist options
  • Save nijikokun/1850603 to your computer and use it in GitHub Desktop.
Save nijikokun/1850603 to your computer and use it in GitHub Desktop.
Probably the hackiest enumerator i've built, Javascript.
// Without the use of yield or enumerable definitions javascript makes enumerating over objects
// very difficult and verbose.
// Goes in Rectangle.js of my Geometry.js class
this.trace = function(f) {
if(this.width() > 1 && this.height() > 1) {
// top
(Rectangle.row(
this.topLeft(), this.width() - 1
)).enumerate(f);
// right
(Rectangle.column(
(this.topRight()).offset(-1), this.height() - 1
)).enumerate(f);
// bottom
(Rectangle.row(
this.width() - 1
)).enumerate(f, function(v) {
return ((this.bottomRight()).offset(-1, -1))['-'](v);
});
// left
(Rectangle.column(
this.height() - 1
)).enumerate(f, function (v) {
return ((this.bottomLeft()).offset(0, -1))['-'](v);
});
} else if(this.width() > 1 && this.height() == 1) {
(Rectangle.row(
this.topLeft(), this.width()
)).enumerate(f);
} else if(this.height() >= 1 && this.width() == 1) {
(Rectangle.column(
this.topLeft(), this.height()
)).enumerate(f);
}
};
this.enumerate = function (f, wrapper) {
if(this.x() < 0 || this.y() < 0)
return;
for(var y = this.pos.y; y < (this.pos.y + this.size.y); y++) {
for(var x = this.pos.x; x < (this.pos.x + this.size.x); x++) {
if(wrapper) wrapper(f(new Vec2d(x, y)));
else f(new Vec2d(x, y));
}
}
};
@leoxi
Copy link

leoxi commented Nov 26, 2013

good job!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment