[JavaScript] Assistance Greatly Appreciated

javascript

#1

I’ve been working on a this project for a while. I originally had it finished and everything was working fine, however the file size after compilation was outrageously large. I therefore had to start over. As far as I can tell this code should work. However, I keep getting a SyntaxError: Unexpected identifier in the console. Any ideas?

This is my javascript so far…

var calendar = require("calendar");
var datetime = require("datetime");

var error = function(code){
    console.log("Error", code);
    if (code === 101){
        console.log("An error has occured! Please restart the program and try again.");
    }
};

var currentDate = function(){
    var now = datetime.now();
    var date = "%s/%s/%s" % (now.month, now.day, now.year);
    return date;
};

var currentDate2 = function(){
    var now = datetime.now();
    var month = now.month;
    if (month === 1){
        fmonth = "Jan";
    } else if (month === 2){
        fmonth = "Feb";
    } else if (month === 3){
        fmonth = "Mar";
    } else if (month === 4){
        fmonth = "Apr";
    } else if (month === 5){
        fmonth = "May";
    } else if (month === 6){
        fmonth = "Jun";
    } else if (month === 7){
        fmonth = "Jul";
    } else if (month === 8){
        fmonth = "Aug";
    } else if (month === 9){
        fmonth = "Sep";
    } else if (month === 10){
        fmonth = "Oct";
    } else if (month === 11){
        fmonth = "Nov";
    } else if (month === 12){
        fmonth = "Dec";
    } else {
        error(101);
    }
    var date = "%s %s %s" % (fmonth, now.day, now.year);
    return date;
};
    
var currentTime = function(){
    var now = datetime.now();
    var time = "%s:%s:%s" % ((now.hour - 4), now.minute, now.second);
    return time;
};

var currentDay = function(){
    var now = datetime.now();
    var today = calendar.weekday(now.year, now.month, now.day);
    return today;
};
    
var currentWeekDay = function(){
    var today = currentDay();
    if (today === 0){
        return "Monday";
    } else if (today === 1){
        return "Tuesday";
    } else if (today === 2){
        return "Wednesday";
    } else if (today === 3){
        return "Thursday";
    } else if (today === 4){
        return "Friday";
    } else if (today === 5){
        return "Saturday";
    } else if (today === 6){
        return "Sunday";
    } else {
        error(101);
    }
};
        
var displayDate = function(){
    console.log("%s, %s, %s" % (currentWeekDay(), currentDate2(), currentTime()));
};

function Member(object){
    this.name = object[0];
    this.monday = object[1];
    this.tuesday = object[2];
    this.wednesday = object[3];
    this.thursday = object[4];
    this.friday = object[5];
    this.checkedIn = object[6];
}

Member.prototype.display = function(){
    return "%s | %s | Checked In: %s" % (this.name, currentDate(), this.checkedIn);
};

Member.prototype.checkIn = function(){
    this.checkedIn = true;
    var today = currentDay();
    if (today === 0){
        this.monday = "Yes";
    } else if (today === 1){
        this.tuesday = "Yes";
    } else if (today === 2){
        this.wednesday = "Yes";
    } else if (today === 3){
        this.thursday = "Yes";
    } else if (today === 4){
        this.friday = "Yes";
    } else {
        this.checkedIn = false;
    }
};

Member.prototype.checkOut = function(){
    this.checkedIn = false;
    var today = currentDay();
    if (today === 0){
        this.monday = "No";
    } else if (today === 1){
        this.tuesday = "No";
    } else if (today === 2){
        this.wednesday = "No";
    } else if (today === 3){
        this.thursday = "No";
    } else if (today === 4){
        this.friday = "No";
    } else {
        error(101);
    }
};

Member.prototype.checkInData = function(){
    console.log("Check-In Data for %s:" % (this.name))
    console.log("Monday: %s" % (this.monday));
    console.log("Tuesday: %s" % (this.tuesday));
    console.log("Wednesday: %s" % (this.wednesday));
    console.log("Thursday: %s" % (this.thursday));
    console.log("Friday: %s" % (this.friday));
};

var poolRoster = []

var displayRoster = function(){
    for n in range(poolRoster.length)){
        console.log(poolRoster[n].display());
    }
};

var addMember = function(){
    var member = new Member(raw_input("Name:"), "No", "No", "No", "No", "No", false);
    poolRoster.push(member);
};

var runCode = function(){
    displayDate();
    console.log("> addMember()");
    addMember();
    console.log("> addMember()");
    addMember();
    console.log("> addMember()");
    addMember();
    console.log("> displayRoster()");
    displayRoster();
};

runCode();

#2

putting your code in jsbin (link), it seems here:

var displayRoster = function(){
    for n in range(poolRoster.length)){
        console.log(poolRoster[n].display());
    }
};

you seem to mix python and JS syntax, jsbin gives a lot of errors about it


#3

Alright… Here’s the updated version.

However, I now receive the following errors…

I receive this error on jsbin
error
ReferenceError: require is not defined
    at lujosar.js:1:2057
I receive this error on repl.it
error
TypeError: datetime.now is not a function
    at currentDay (https://replit.org/data/web_project/9d612f7003f2fe13f5058ac57eec0852/index.js:58:24)
    at currentWeekDay (https://replit.org/data/web_project/9d612f7003f2fe13f5058ac57eec0852/index.js:64:17)
    at displayDate (https://replit.org/data/web_project/9d612f7003f2fe13f5058ac57eec0852/index.js:85:33)
    at runCode (https://replit.org/data/web_project/9d612f7003f2fe13f5058ac57eec0852/index.js:161:5)
    at https://replit.org/data/web_project/9d612f7003f2fe13f5058ac57eec0852/index.js:172:1

Any Ideas?


#4

require is not part of the JavaScript language. We use require to load dependency. But you need to add a dependency such as require.js or node.js to first add that function and ability.

In JavaScript, you can create a new date object using new Data(). Here’s some info for you on MSD.


#5

Data structure versus logic

const days = ['Sunday', 'Monday', 'Tuesday',
  'Wednesday', 'Thursday', 'Friday', 'Saturday'];

const months = [
  'January', 'February', 'March', 'April', 'May', 'June',
  'July', 'August', 'September', 'October', 'November', 'December'
];

let today = new Date();

let $date = `Today's date: ${days[today.getDay()]}, ${months[today.getMonth()]}\
  ${today.getDate()}, ${today.getFullYear()}.`;

console.log($date);
Today's date: Tuesday, August 8, 2017.

#6

You can use .toLocaleDateString() and pass in the options to configure the formatted date that you want.

var getTodayDate = function() {
    var now = new Date(),
        options = {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        };

    return "Today's date is " + now.toLocaleDateString('en-US', options);
};

console.log(getTodayDate());

Let JavaScript handle the constants and format it to the locale that you want. Here’s a demo. Plus, here’s the documentation on MDN web docs.

FYI: It’s a better practice to format date and time to the viewer’s locale as different parts of the world are used to dates being formatted in a particular way. US wants Month then Day then Year, whereas Europe wants Day then Month then Year.


#7

I wanted to demonstrate something with minimal abstraction. The OP is in the US, I believe.

Here is an ES6 version of your function…

const getTodayDate = () => {
  const now = new Date(),
    options = {
      weekday: 'long',
      month: 'long',
      day: 'numeric',
      year: 'numeric'
    };

  return `Today's date is ${now.toLocaleDateString('en-US', options)}`;
};

console.log(getTodayDate());

#8

We wouldn’t want to use a const here, as now is variable. Therefore, we’d still want to build a function that gets us a formatted date for the current day.

For ES6, we can then use let instead of var for the now variable, like this:

var getTodayDate = function() {
    let now = new Date(),
        options = {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        };

    return "Today's date is " + now.toLocaleDateString('en-US', options);
};

console.log(getTodayDate());

Cheers


#9

How is it varying? Once defined it never changes.


#10

JavaScript lives in the browser, which then means now can vary. If I have the web page open and leave it open over the course of 2 days, then the date will change. Right?

Also, the time will change too. The above function can vary. If you want to provide say Date and Time, then you’d want it to vary. If you want it to provide the current “now”, it needs to vary.

If however you want it to only capture now once and then hold it as a constant until that page is refreshed, then that’s an edge case where you could use a constant.


#11

A lot of times we’ll design interfaces that adapt to the viewer’s locale (not always, as it’s up to the developer/project). But if we want to make it more readable regardless of where we live when they view the web page, then we think about allow the timezone to change.

That said, I have built apps where we set a fixed timezone for when a sale starts and ends.

But it depends upon the needs of the application and for whom it will serve.


#12

In the scope of the function, now is static. Any time we instantiate a new Date object, it is a snapshot, so also static.

The date may change, but has no real bearing. When we run the function, now is a new snapshot.


#13

Respectfully, I disagree. Here’s a demo to show that the date and time are relative to when the function is called.

var getTodayDate = function() {
    var now = new Date(),
        options = {
            weekday: 'long',
            year: 'numeric',
            month: 'long',
            day: 'numeric'
        };

    var message = "Today's date is " + now.toLocaleDateString('en-US', options);
  
    message += " and the current time is " + now.toLocaleTimeString('en-US', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
    });

    return message;
  
};

console.log(getTodayDate());

// Demonstrate grabbing now...5 seconds later.
setTimeout(function(){
    console.log(getTodayDate());
}, 5000);

You’ll see that the time is 5 seconds later, demonstrating that it is not static.


#14

But it is static. Each time the function exits, it is garbage collected. All your code is doing is calling the function twice. The time will change, obvously, but each time, now is static.


#15

True. In this case now is static within the function’s scope. You call it once and that’s it.

If we go to MDN and consult the documentation, it says:

Constants are block-scoped, much like variables defined using the let statement. The value of a constant cannot change through re-assignment, and it can’t be redeclared.

And if we want to declare it as a constant, then the typically naming convention is to make it all caps to say, "Hey this is a CONSTANT.` (side note: Naming conventions are up to the team to decide for standardization.)

Typically in apps, we reserve constants for that purpose: I don’t want this variable to change ever. Most times we set it up in global or app scope to reuse it over and over again.

Technically, yes, within this function and its scope, it is constant to that function only because we are not changing its value.

However, we typically don’t use const in this way. We use let in EC6 or var in prior versions. Why? Because of intent. For example, setting days of the week is constant. Setting a version number is constant. Setting an offset might be a constant.

Within this function, however, every time you call it, it changes. Therefore, even though it only holds state for that function’s execute, we can read it and know that it changes. It’s intent is not to remain constant, but to change.

Whereas with const DAYS_OF_WEEK = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; this variable remains constant every single time it’s used. It never changes unless you go in there and manually update the file.


#16

Let me elaborate just a bit more:

We select things like const over let when:

  • we are guarding the value and do not want it to change.
  • we are communicating the intent that we do not want it to change.

@mtf In your snippet of code, you are communicating that now within the scope of the function is constant and you are guarding that value to ensure that it never changes.

Therefore, if that is what you intended by using const, then that is the right tool.

ES6 is different. It takes a different mindset. So teams, me included, are used to reserving constant declarations for different edge cases.

When I look at different repositories for JavaScript libraries and frameworks, I see different implementations.

I can see the argument on both sides. Yours is right if that’s what you intend in your code.


#17

If there was a loop inside the function, then I would use let to declare it, and define it in the loop. But since it is static, using const just confirms that and the reader does not expect it to change. Any of the keywords, var, let, const used in the manner above will be fine as I see it, so long as we are sure to give block scope to the variable so it does not leak into global scope.


#18

Here’s how I interpret it:

  1. The object has both data and functionality.
  2. now is an instance of Date
  3. The object can change when we change the data within it.
  4. We can add new properties to the object via it’s prototype and change it.

Therefore, I interpret it not as a static, but as a variable that is holding an instance of an object. Objects are not static. They have both data and functionality. You can change their data and redefine them.

You on the other hand view it as static because the variable is holding a reference to the object and that reference does not change. It’s always going to be that object, even if the object itself changes. Right? That’s your argument for using const.

I can see that. Both points of view have validity.

You’d be amazed at how many times engineers sit in meetings and argue about this very thing.

This discussion is a perfect example of how code construction is dependent upon the team and it’s standards.

Let me say that I’m not arguing with you. I’m merely expressing what I see and have seen over the years on my teams. Your point of view is valid.

I think we beat that issue to death and can move on now. Don’t you?


#19

The more I think about it, the variable itself does not change, as we want it to remain pointing to that object. The object may change, but not the reference to the variable. Therefore, @mtf you changed my mind. Great job.


#20

It makes sense that even while the function doesn’t actually change it, it could, so I see what you are saying. Funny thing is, when I first mocked up the code it did use let and based upon my thinking in the last post, I switched it. Fuzzy thinking. Sorry to put up an argument, and thanks for the background reading.