0
\$\begingroup\$

I am checking three elements on the DOM to see if they are empty or not so that I can run only the Ajax calls that I should run and save on overall bandwidth. The code works but it "smells bad". Here is my source.

const processValues = (area, city, text) => {
    if (area.val() && city.val() && text.val()) {
        return 'all';
    } else if (area.val() && city.val() && !text.val()) {
        return 'areaCity';
    } else if (area.val() && !city.val() && text.val()) {
        return 'areaText';
    } else if (area.val() && !city.val() && !text.val()) {
        return 'city';
    } else if (!area.val() && city.val() && text.val()) {
        return 'cityText';
    } else if (!area.val() && !city.val() && text.val()) {
        return 'text';
    } else if (!area.val() && city.val() && !text.val()) {
        return 'city';
    } else {
        return 'none';
    }
};

I will be repeating this check in a few methods and I will be using a switch statement in those methods with the returned string values. If there is a better way to do this, I would appreciate it.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

After speaking with some friends, this is seen as the best solution. One adjustment to the return values was required however; change the casing from camel case to title case. I am also using constants to make sure that return values can be consistently used properly.

/**
 * Check the three dom elements to see if they are empty or not and return detailed result.
 * @param {jQuery|HTMLElement} area Area input field.
 * @param {jQuery|HTMLElement} city City input field.
 * @param {jQuery|HTMLElement} text Text input field.
 * @return {string} Detailed result of which input fields are empty.
 * If all are filled, returns "all".
 * If none are filled, returns empty string.
 */
export const processValues = (area, city, text) => {
    const a = (area.val()) ? 'Area' : '';
    const c = (city.val()) ? 'City' : '';
    const t = (text.val()) ? 'Text' : '';
    if (a !== "" && c !== "" && t !== "") {
        return "all";
    } else {
        return a + c + t;
    }
};

export const ALL = "all";
export const AREA_CITY = "AreaCity";
export const AREA_TEXT = "AreaText";
export const AREA = "Area";
export const CITY_TEXT = "CityText";
export const CITY = "City";
export const TEXT = "Text";
```
\$\endgroup\$
1
  • \$\begingroup\$ Please try to use either "" or '' at all occurrences. Please also try to use better naming than a, c, t. Why do you need to export these constants? Where is none? \$\endgroup\$ Apr 28, 2021 at 6:27

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.