I run into this often. I have two functions very similar, that if I combine would be more DRY but if I didn't would be easier to read and make more sense.
In this case I have two implementations of fade, one using setInterval
and one using setTimeout
.
How do I not get stuck deciding between Dry vs. readability. I hope this is not an opinion question that is not answerable.
/*fade
** d:none
** n:uses setTimeout
**
*/
NS.prototype.fade = function (direction, max_time) {
var statics = {},
elements = this;
statics.elapsed = 0;
statics.granularity = 10;
if (statics.timeout_id) {
clearTimeout(statics.timeout_id);
}
(function next() {
var kindex,
opacity;
statics.elapsed += statics.granularity;
if (direction === 'up') {
for (kindex in elements) {
if (elements.hasOwnProperty(kindex)) {
opacity = statics.elapsed / max_time;
elements[kindex].style.opacity = opacity;
}
}
} else if (direction === 'down') {
for (kindex in elements) {
if (elements.hasOwnProperty(kindex)) {
elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
}
}
}
if (statics.elapsed < max_time) {
statics.timeout_id = setTimeout(next, statics.granularity);
}
}());
};
/*fadeL
** d:none
** n:(L)inear. Uses setInterval. Better for short animations.
**
*/
NS.prototype.fadeL = function (direction, max_time) {
var statics = {},
elements = this;
statics.elapsed = 0;
statics.granularity = 10;
if (statics.timeout_id) {
clearInterval(statics.timeout_id);
}
(function next() {
var kindex,
opacity;
statics.elapsed += statics.granularity;
if (!statics.timeout_id) {
statics.timeout_id = setInterval(next, statics.granularity);
}
if (direction === 'up') {
for (kindex in elements) {
if (elements.hasOwnProperty(kindex)) {
opacity = statics.elapsed / max_time;
elements[kindex].style.opacity = opacity;
}
}
} else if (direction === 'down') {
for (kindex in elements) {
if (elements.hasOwnProperty(kindex)) {
elements[kindex].style.opacity = (max_time - statics.elapsed) / max_time;
}
}
}
if (statics.elapsed > max_time) {
clearInterval(statics.timeout_id);
}
}());
};