I am comparing the index of the current component displayed in the viewport against an array of all the components on the screen to determine to direction the user in scrolling.

Does this function have too many concerns? and can the if statements be reduced to something cleaner?

function getDirection(component) {
    let direction;
    if (!this.lastComponentInViewport) {
      direction = "none";
    } else {
      let oldIndex = this.components.indexOf(this.lastComponentInViewport);
      let newIndex = this.components.indexOf(component);

      if (newIndex === oldIndex) direction = "none";

      if (newIndex > oldIndex) direction = "next";

      if (newIndex < oldIndex) direction = "previous";
    return direction;
  • \$\begingroup\$ I could start with removing the outer if/else statement and combine here: if (newIndex === oldIndex || !this.lastComponentInViewport) direction = "none"; \$\endgroup\$
    – dandan
    Commented Oct 31, 2019 at 2:44
  • 1
    \$\begingroup\$ Welcome to Code Review. You are welcome to answer your own question. Addressing main concerns in comments to questions is frowned upon. (Here, I suggest editing afterthoughts to the question proper.) \$\endgroup\$
    – greybeard
    Commented Oct 31, 2019 at 6:07

1 Answer 1


"none" can be treated as a default returned value, thus eliminating multiple occurrences of direction = "none" assignment.
In that way it'd be enough to just consider non-none cases:

function getDirection(component) {
    let oldIndex, newIndex,
        lastComp = this.lastComponentInViewport;

    if (lastComp) {
        oldIndex = this.components.indexOf(lastComp);
        newIndex = this.components.indexOf(component);
        if (newIndex > oldIndex) return "next";
        if (newIndex < oldIndex) return "previous";
    return "none";

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.