@tostershmoster

Как можно оптимизировать данный код?

private isThumbsCollision(): boolean {
  let fromEdge: number;
  let toEdge: number;
  let thumbSize: number;

  if (this.settings.isVertical) {
    thumbSize = this.to.tooltip.element.getBoundingClientRect().height;
    fromEdge = this.from.element.getBoundingClientRect().top;
    toEdge = this.to.element.getBoundingClientRect().top;
  } else {
    thumbSize = this.to.tooltip.element.getBoundingClientRect().width;
    fromEdge = this.from.element.getBoundingClientRect().right;
    toEdge = this.to.element.getBoundingClientRect().right;
  }
  return toEdge - fromEdge <= thumbSize;
}
  • Вопрос задан
  • 153 просмотра
Пригласить эксперта
Ответы на вопрос 2
sergiks
@sergiks Куратор тега JavaScript
♬♬
Если оптимизировать = «чтобы без повторений», можно потерять читаемость:
private isThumbsCollision(): boolean {
  const prop = [
    {size: 'width', side: 'right'},
    {size: 'height', side: 'top'},
  ][+this.settings.isVertical];

  return this.to.tooltip.element.getBoundingClientRect()[prop.size] 
    >= this.to.element.getBoundingClientRect()[prop.side]
    - this.from.element.getBoundingClientRect()[prop.side];
}
Ответ написан
@mn3m0n1c_3n3m1
const getRect = (el) => el.tooltip.element.getBoundingClientRect();

function isThumbsCollision({from, to, settings}) {
    const fromRect = getRect(from);
    const {top, right, height, width} = getRect(to);

    if (settings.isVertical)
        return top - fromRect.top <= height;

    return right - fromRect.right <= width
}
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы