0
私のコードの品質を最適化する方法を探していたのですが、やっとDRYという概念が出てきました。私はできる限りベストを尽くそうとしますが、時には2行または3行のコードを除いて2つの関数を書く必要があります。そして、最善の方法を見つけようとしています。それを整理する。DRYの原則をJavaScriptに適用すると、このコードを最適化するのに役立ちますか?
ここに私の "質問"があります。数週間前に書いた2つの関数は、最後に3行を除いて基本的に同じですが、1つは加算で、もう1つは減算で行います。私は他の開発者から以下のコードをどのように最適化するかについていくつかの情報を得たいと思っていますまたはには、同様の問題を解決した無関係なコードの例があります。
/**
* Go to the previous notification
*
* @private
* @param {object} cl Click event details (ex. {id: 'linkId', ss: '_', index: '1', e: event})
* @memberOf APP.devices
*/
function slideNext (cl) {
var button = $('#' + cl.id + cl.ss + cl.index),
index = cl.index - 1,
slider = devices[index].container.find('.slideContainer'),
// In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
if (button.hasClass('disabled')) {
return false;
}
slider.find('.active').removeClass('active').prev().addClass('active');
disableButtons(index);
slider.animate({'right': slidePos + notificationOffset}, 200, function() {
determineButtonState(index);
});
updatePositionContext(index);
}
/**
* Advance to the next notification
*
* @private
* @param {object} cl Click event details
* @memberOf APP.devices
*/
function slidePrev (cl) {
var button = $('#' + cl.id + cl.ss + cl.index),
index = cl.index - 1,
slider = devices[index].container.find('.slideContainer');
// In order to get the value of the 'right' position we must take the (container width - slider width - left position - right-margin)
slidePos = (slider.parent().width() - slider.width()) + (slider.position().left * -1) + (parseFloat(slider.css('margin-right')) * -1);
if (button.hasClass('disabled')) {
return false;
}
slider.find('.active').removeClass('active').next().addClass('active');
disableButtons(index);
slider.animate({'right': slidePos - notificationOffset}, 200, function() {
determineButtonState(index);
});
updatePositionContext(index);
// Load more notifications once user get's close to the end of the current set of notifications
if (slider.find('.active').nextAll().length == 3) {
getMoreNotifications(index);
}
}
私は推測するには理にかなっていると思います。他の人が取るさまざまなアプローチをもっと見ることにもっと興味がありますが、あなたが提案したようなことをやってしまう可能性が最も高くなります。ありがとう。 – Charles