Ernie sent this ruby snippet and marveled at its brilliant simplicity:
class Date
def at_some_point
(at_midnight..tomorrow.at_midnight).to_a.rand
end
end
Date.today.at_some_point # => Tue May 21 10:23:00 -0500 2008
Date.today.at_some_point # => Tue May 21 02:10:00 -0500 2008
Date.today.at_some_point # => Tue May 21 18:28:00 -0500 2008
Date.today.at_some_point # => Tue May 21 07:25:00 -0500 2008
I recalled using Date.prototype in JavaScript in the past to add some helpful date functions, so I thought I'd see if I could write a similar function just as elegantly:
Date.prototype.atSomePoint = function() {
return new Date(rand(this.atMidnight().valueOf(), this.tomorrow().atMidnight().valueOf()));
};
new Date().atSomePoint(); \\ Wed May 21 2008 06:33:28 GMT-0400 (Eastern Daylight Time)
new Date().atSomePoint(); \\ Wed May 21 2008 12:57:13 GMT-0400 (Eastern Daylight Time)
new Date().atSomePoint(); \\ Wed May 21 2008 08:37:44 GMT-0400 (Eastern Daylight Time)
Unfortunately .atMidnight() and .tomorrow() don't exist in JavaScript's Date object by default (that I know of), so I had to write those helpers as well as a random number helper, rand():
Date.prototype.atMidnight = function() {
this.setHours(0);
this.setMinutes(0);
this.setSeconds(0);
return this;
};
Date.prototype.tomorrow = function() {
this.setDate(this.getDate() + 1);
return this;
};
function rand(lowerBound, upperBound) {
return Math.floor((upperBound - (lowerBound - 1)) * Math.random()) + lowerBound;
}
While I probably would never find a use for .atSomePoint(), it certainly was easy enough to write.