#Can function be simplified

9 messages · Page 1 of 1 (latest)

idle oxide
#
function checkValue(value: string | null) {
  value = (value as string).trim();
  if (value == null || value === null || value === "" || value == "" || value === "null" || value == "null") {
    return null;
  }
  else {
    return value;
  }
}

export default {checkValue} as
    {checkValue: (value: string | null) => string | null};

Checking to verify if string is empty running. im running all these tests to cover my bases just wanted to know if there something could be done to simplify things?

karmic mist
#

yes, this could be simplified
below the different steps that can be taken:

#

arrow == and === both check for equality, however === also accounts for the type, nowadays, using === is recommended over ==

function checkValue(value: string | null) {
    value = (value as string).trim();
    if (value === null || value === "" || value === "null") {
        return null;
    }
    else {
        return value;
    }
}
#

arrow value = (value as string).trim(); is wrong and might crash at runtime
you wrote value could be null, if it is null, it will try to call the trim method on it, and will fail
casts only work with the type, they don't change the value of the variable
instead, do something like value &&= value.trim();, which will only execute if value is truthy

function checkValue(value: string | null) {
    value &&= value.trim();
    if (value === null || value === "" || value === "null") {
        return null;
    }
    else {
        return value;
    }
}
#

arrow checking for value === "null" is not something I'd recommend doing
a string is a string, if you want null, then pass null
I would not consider "null" being a replacement value for null

function checkValue(value: string | null) {
    value &&= value.trim();
    if (value === null || value === "") {
        return null;
    }
    return value;
}
#

arrow can be simplified into

function checkValue(value: string | null) {
    value &&= value.trim();
    return value ? value : null;
}
#

arrow you can also simplify the export, no need the fiddle with the types there

function checkValue(value: string | null) {
    value &&= value.trim();
    return value ? value : null;
}

export default { checkValue };
#

arrow finally, I'd probably go with a named export instead of a default export being an object with a function

export function checkValue(value: string | null) {
    value &&= value.trim();
    return value ? value : null;
}
#

@idle oxide