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;
}),
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";
}
You must log in to answer this question.
Explore related questions
See similar questions with these tags.
if (newIndex === oldIndex || !this.lastComponentInViewport) direction = "none";\$\endgroup\$