0

I need help in making improvements in my code. I want a safety check-in getDateObject itself.

function getDateObject(dateStr, format) {
    if(not valid date format){
        //show some error.
        return false;
    } else {
        return {
            dateStr:dateStr,
            isFutureDate: function(){
                //some logic
            }
        }
    }
}

var dtObj = getDateObject('02/02/2020','MM/YYYY');
if(dtObj) { 
    // If I dont not put this then I get error. I do not want this extra check here. How should I integrate it in getDateObject function.
    dtObj.isFutureDate();
}
Devang
  • 454
  • 1
  • 8
  • 18
Triven
  • 351
  • 1
  • 4
  • 17
  • Did you explore the option of using something like `if(typeof YourVariable == "")…`? – FDavidov May 01 '20 at 05:31
  • @FDavidov: Yes I know about it but not sure where and how exactly I should place this check in my main function. – Triven May 01 '20 at 05:33
  • 1
    Instead of returning `false` you could always return a date object, and the date object could carry a state if it is valid or not, like [monent.js](https://momentjs.com/docs/#/parsing/is-valid/) does. But at some point, you would need to do the check if the date is valid, so I don't think that you will get around such a check, in one way or the other. – t.niese May 01 '20 at 05:35
  • @palaѕн This question seems to be closed with incorrect reference. If I have mentioned something about date that does not mean that this question is about validating date. My question is not at related to dates. – Triven May 01 '20 at 05:40
  • @t.niese : Thanks I got the hint.. I will now deal with it. – Triven May 01 '20 at 05:47
  • But as I said, at some point when you want to retrieve information from that object you need to check if the object either exits, f its state is valid, or handle an exception. So I don't see that you can remove a check with that, the check might just look different. – t.niese May 01 '20 at 05:56
  • 1
    @Triven, there are some people in this forum that appear to feel in a western movie and tend to shoot too fast (closing perfectly legitimate questions), and that is a pity since it has negative impact on this extremely useful forum. Anyway, the `typeof` operator/function returns a string that may serve you to detect a problem and act accordingly. You may wish to chec this site: https://www.w3resource.com/javascript/operators/typeof.php. – FDavidov May 02 '20 at 08:33

0 Answers0