Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
uncle blog
Nov 18, 2012

Speaking of Typescript: what's the best, most elegant way to check and assign a value that might be undefined?

code:

// manyThings: {id: string, subThing: string}[] 

const thingIWant = manyThings.find((thing) => thing.id === "123").subThing;  // This gives the error that it might possible be undefined, which I get

const thingIWant = manyThings.find((thing) => thing.id === "123").subThing ? manyThings.find((thing) => thing.id === "123").subThing : "oops, nothing there";  // Still not okay

const thingIWant = manyThings.find((thing) => thing.id === "123") && manyThings.find((thing) => thing.id === "123").subThing ? manyThings.find((thing) => thing.id === "123").subThing : "oops, nothing here" // Now I honestly can't understand why TS complains

// So what I end up doing is this
const thingIWant = manyThings.find((thing) => thing.id === "123") ? manyThings.find((thing) => thing.id === "123") : {subThing: "oops, nothing here"};
const thingIActuallyWant = thingIWant.subThing;

This feels stupid, so I guess there is a better, easier way to accomplish the same thing?

Adbot
ADBOT LOVES YOU

nexus6
Sep 2, 2011

If only you could see what I've seen with your eyes

Dominoes posted:

Typescript is an improvement to the language, but requires a build step. If your process has one anyway, use it. If not, balance easier-to-use code with skipping the build and config TS requires.

Hell yeah, front end build tools. Because there aren't enough of them.

fsif posted:

Look if you're just making a website that needs a hamburger menu and maybe a modal or two you can absolutely (and probably should) use vanilla JS. There's no need to overengineer every project that touches JS.

Comedy answer: jQuery

IAmKale
Jun 7, 2007

やらないか

Fun Shoe

uncle blog posted:

Speaking of Typescript: what's the best, most elegant way to check and assign a value that might be undefined?

This feels stupid, so I guess there is a better, easier way to accomplish the same thing?

If you’re using at least TypeScript 3.7 you can use optional chaining:

code:
const thingIWant = manyThings.find((thing) => thing.id === "123")?.subThing;

Impotence
Nov 8, 2010
Lipstick Apathy

nexus6 posted:

Comedy answer: jQuery

The biggest thing I wanted from jQuery exists in vanilla now and I love it

$ -> querySelector
$$ -> querySelectorAll


uncle blog
Nov 18, 2012

IAmKale posted:

If you’re using at least TypeScript 3.7 you can use optional chaining:

code:
const thingIWant = manyThings.find((thing) => thing.id === "123")?.subThing;

Thanks, but we're still at 3.5 I'm afraid.

marumaru
May 20, 2013



A Cup of Ramen posted:

don't suppose anyone would have any course recommendations that cover JS really well would they?

freecodecamp had a lot of really good stuff back when i used it

Data Graham
Dec 28, 2009

📈📊🍪😋



Biowarfare posted:

The biggest thing I wanted from jQuery exists in vanilla now and I love it

$ -> querySelector
$$ -> querySelectorAll

How about AJAX? I'll be writing a site and thinking "Hmm I should do this in vanilla" and then realize I have five hundred AJAX calls to do. Every time I look up "how to do ajax in vanilla JS" it basically tells me to write my own XMLHttpRequest.onreadystatechange handlers like a loving caveman

nexus6
Sep 2, 2011

If only you could see what I've seen with your eyes

Data Graham posted:

How about AJAX? I'll be writing a site and thinking "Hmm I should do this in vanilla" and then realize I have five hundred AJAX calls to do. Every time I look up "how to do ajax in vanilla JS" it basically tells me to write my own XMLHttpRequest.onreadystatechange handlers like a loving caveman

http://youmightnotneedjquery.com/

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Tei
Feb 19, 2011
Probation
Can't post for 4 days!
I understand that jquery is obsolete now that we have better things,

but theres still reasons to use it, and is a upgrade from "vanilla js".

God knows javascript is a terrible language,, and browsers are a idiots environment. The frameworks arms race started because vanilla js over a browser can be a miserable experience.

nexus6
Sep 2, 2011

If only you could see what I've seen with your eyes

Tei posted:

I understand that jquery is obsolete now that we have better things,

but theres still reasons to use it, and is a upgrade from "vanilla js".

God knows javascript is a terrible language,, and browsers are a idiots environment. The frameworks arms race started because vanilla js over a browser can be a miserable experience.

Also, jQuery doesn't require you to compile/transpile your code. You can just drop it in.

marumaru
May 20, 2013



Tei posted:

but theres still reasons to use it, and is a upgrade from "vanilla js".

yes, if you are not interested in keeping up with contemporary technology, are a self-proclaimed "back-end only!" developer with no interest in learning any front-end technologies at all, or if you have been using jquery for the last 45 years anyway and just don't want to learn new stuff. those are (relatively) valid reasons.

javascript has gotten a lot better since es2015. there's a reason why so many people use it and like it.

if you don't need a lot of javascript (and you should absolutely not be using javascript unless you actually have to, despite what some folks might tell you) not using jquery is especially useful, because jquery still has to be downloaded, (possibly) uncompressed and parsed. sure it might be fast for most people, but it's not free.

some of the most common usecases are even in vanilla js now:
code:
$.getJSON('/my/url', function(data) {
});
code:
fetch(`/my/url`)
  .then(function(data) {
  })
or

code:
$('.my #awesome selector');
code:
document.querySelectorAll('.my #awesome selector');
more here:

Data Graham
Dec 28, 2009

📈📊🍪😋



Sweet. I see that it means more boilerplate than $.ajaxSetup if I want to (say) add a CSRF token header into every call, but that's what the Django docs say to do now (replacing their previous jQuery-centric docs), so it's clear which way the wind is blowing.

Dominoes
Sep 20, 2007

Data Graham posted:

that's what the Django docs say to do now
I'm surprised by how robust and (relatively) timeless Django is. There's a steady stream of new backend frameworks in Python, Go, Rust etc, advertising fast speeds, async-first etc, but after closer examination, are missing basic features Django provides. In some cases these are available as third party modules that may or may not work together. In other cases, they're not.

Dominoes fucked around with this message at 14:20 on Nov 25, 2020

Data Graham
Dec 28, 2009

📈📊🍪😋



Yeah, seriously. Like yeah I want user management out of the box. And it feels like its momentum is picking up if anything, not slacking.

Data Graham fucked around with this message at 14:24 on Nov 25, 2020

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

uncle blog posted:

Thanks, but we're still at 3.5 I'm afraid.

JavaScript code:
(thing.find() || {}).prop
you can also get optional chaining with a babel plugin without upgrading typescript

prom candy
Dec 16, 2005

Only I may dance
That'll probably complain that .prop doesn't exist on {}

Try

code:
const thing = myThings.find(t => t.id === "123")
const subThing = thing && thing.subThing ? thing.subThing : "my fallback string"
Edit: Also upgrade to 3.7, optional chaining is so good

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself

prom candy posted:

That'll probably complain that .prop doesn't exist on {}

The "something" variable is just typed as a string or undefined. Perfectly valid



Also here's the babel plugin if for some reason you can't upgrade:

https://babeljs.io/docs/en/babel-plugin-proposal-optional-chaining

prom candy
Dec 16, 2005

Only I may dance
Oh nice, I swear I used to try to do those kinds of substitutions and the compiler would always yell at me, maybe that was with an older version or a different configuration though

Doom Mathematic
Sep 2, 2008

uncle blog posted:

Speaking of Typescript: what's the best, most elegant way to check and assign a value that might be undefined?

code:

// manyThings: {id: string, subThing: string}[] 

const thingIWant = manyThings.find((thing) => thing.id === "123").subThing;  // This gives the error that it might possible be undefined, which I get

const thingIWant = manyThings.find((thing) => thing.id === "123").subThing ? manyThings.find((thing) => thing.id === "123").subThing : "oops, nothing there";  // Still not okay

const thingIWant = manyThings.find((thing) => thing.id === "123") && manyThings.find((thing) => thing.id === "123").subThing ? manyThings.find((thing) => thing.id === "123").subThing : "oops, nothing here" // Now I honestly can't understand why TS complains

// So what I end up doing is this
const thingIWant = manyThings.find((thing) => thing.id === "123") ? manyThings.find((thing) => thing.id === "123") : {subThing: "oops, nothing here"};
const thingIActuallyWant = thingIWant.subThing;

This feels stupid, so I guess there is a better, easier way to accomplish the same thing?

I would probably go with:

JavaScript code:
const thing = manyThings.find((thing) => thing.id === "123")
const subThing = thing === undefined ? 'oops, nothing here' : thing.subThing
If you're desperate to do it in a single line of code:

JavaScript code:
const subThing = (manyThings.find((thing) => thing.id === "123") || { subThing: 'oops, nothing here' }).subThing

Null of Undefined
Aug 4, 2010

I have used 41 of 300 characters allowed.
jQuery still has its place but modern javascript has adopted so much of the good stuff from it it's really only needed for a few things.

I do find it funny that the main thing jQuery is made fun of (being used in instances where it's not strictly necessary, bogging down websites that don't need it) applies just as much to pretty much every other modern front-end framework, but jQuery is still the most maligned.

PT6A
Jan 5, 2006

Public school teachers are callous dictators who won't lift a finger to stop children from peeing in my plane

Data Graham posted:

Yeah, seriously. Like yeah I want user management out of the box. And it feels like its momentum is picking up if anything, not slacking.

Yeah, it's pretty great, and fairly trivially extensible if you can't do exactly what you want with the built-in functionality.

Tei
Feb 19, 2011
Probation
Can't post for 4 days!
I find the => operator ugly

Anony Mouse
Jan 30, 2005

A name means nothing on the battlefield. After a week, no one has a name.
Lipstick Apathy
I'll never understand anyone who turns up their nose at TypeScript. You can use as few or as many of its features as you want; you don't even need to change how you write code, 95% of types can be inferred automatically. Even in pre-existing codebases you can easily configure vanilla JS and TS to play nice together, you don't have to rewrite anything. TypeScript has saved me magnitudes more time and headaches than it costs to install and configure it, helps keep code "self documenting", and helps me think about my data structures and organization more intentionally.

nexus6
Sep 2, 2011

If only you could see what I've seen with your eyes

Null of Undefined posted:

jQuery still has its place but modern javascript has adopted so much of the good stuff from it it's really only needed for a few things.

I do find it funny that the main thing jQuery is made fun of (being used in instances where it's not strictly necessary, bogging down websites that don't need it) applies just as much to pretty much every other modern front-end framework, but jQuery is still the most maligned.

Yeah, modern JS requires 16 million dependencies that you install with npm.

Bruegels Fuckbooks
Sep 14, 2004

Now, listen - I know the two of you are very different from each other in a lot of ways, but you have to understand that as far as Grandpa's concerned, you're both pieces of shit! Yeah. I can prove it mathematically.

Null of Undefined posted:

jQuery still has its place but modern javascript has adopted so much of the good stuff from it it's really only needed for a few things.

I do find it funny that the main thing jQuery is made fun of (being used in instances where it's not strictly necessary, bogging down websites that don't need it) applies just as much to pretty much every other modern front-end framework, but jQuery is still the most maligned.

There was a point in the distant past where JQuery was a useful - back when having to support IE6 was useful. Then we reached a certain point where browsers could do natively most of what JQuery was doing, and using JQuery for say, event handlers would actually solve no problems and introduce new ones - e.g. on some browsers, a mousemove event bound with jquery would spend about 70% CPU time in "event normalization" (e.g. taking the native event objects and converting them into an internal JQuery form to try to minimize the browser differences in event handling.) Most of the features the library introduced (e.g. the JQuery selector library) were horrifically slow and cache after cache was tacked on in order to get them to function with some appropriate degree of performance, and the caches would introduce memory leaks, etc.

One of the big reasons AngularJS was thrown out for Angular2 turned out to be this JQuery/JQLite dependency - even the small subset of JQuery present in JQLite was bad enough for performance that they had to effectively start from scratch.

Even the features that work that aren't slow suck. JQuery promises for instance are usable, but suck (https://thewayofcode.wordpress.com/2013/01/22/javascript-promises-and-why-jquery-implementation-is-broken/.

I mean, if you have to slap together something quick that needs to run in an old IE browser, I wouldn't knock JQuery. But it's caused more problems than it solves for many years now.

Data Graham
Dec 28, 2009

📈📊🍪😋



Something I've been doing lately when I can't sleep is dig up old projects from like 2009 that I had written in ColdFusion or Perl/CGI or some poo poo and update them to be on something modern and sane. In the process I'm taking the opportunity to try to excise jQuery if at all possible.

Now that I know about fetch and the various querySelector things, I think the only areas where it's not possible to get rid of it are the plugins I have on these sites like carousels and such that are themselves based on jQuery. I'd imagine those are going to be the last things to get their installed-base bulk out from under the jQuery inertia.

New Coke
Nov 28, 2009

WILL AMOUNT TO NOTHING IN LIFE.
I've been maintaining an Angular app that allows employees to clock in via a web portal, and some of them are seeing the time appear incorrectly. First off, I've added a bit of logging to try to get some visibility into the problem and confirm my suspicion; that some of their browsers are using an incorrect timezone.

My first question, just so that I know I'm on the right track, is whether or not this line of code is telling me what I think it is:

code:
new Date().getTimezoneOffset()
I know what this should be, given my location, and based on the logging I've implemented, the user that has been experiencing this does get a different result for this. Am I correct in concluding that the browser's timezone is the issue here?

My second question is how this actually happens, or more importantly how the user can correct this. The offending browser is Chrome 81 for Android, and as far as I can tell there's no way to view or change the timezone; it's just set automatically using the system settings (yet the clock for this device is actually set correctly).

Finally, since all the users are in the same timezone, just hard coding the app to display correctly for the specified timezone is also an option. Do Angular date pipes provide a way to do this? Ideally, this would accommodate Daylight Savings, so that this doesn't break again in the spring.

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer

Data Graham posted:

Something I've been doing lately when I can't sleep is dig up old projects from like 2009 that I had written in ColdFusion or Perl/CGI or some poo poo and update them to be on something modern and sane. In the process I'm taking the opportunity to try to excise jQuery if at all possible.

Now that I know about fetch and the various querySelector things, I think the only areas where it's not possible to get rid of it are the plugins I have on these sites like carousels and such that are themselves based on jQuery. I'd imagine those are going to be the last things to get their installed-base bulk out from under the jQuery inertia.

Most WordPress form managers are built with jQuery, and they're too useful to not have. I've wanted to create my own form manager that's basically Contact Form 7 that actually works reliably and stores submissions, but :effort:

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

New Coke posted:

I've been maintaining an Angular app that allows employees to clock in via a web portal, and some of them are seeing the time appear incorrectly. First off, I've added a bit of logging to try to get some visibility into the problem and confirm my suspicion; that some of their browsers are using an incorrect timezone.

My first question, just so that I know I'm on the right track, is whether or not this line of code is telling me what I think it is:

code:
new Date().getTimezoneOffset()
I know what this should be, given my location, and based on the logging I've implemented, the user that has been experiencing this does get a different result for this. Am I correct in concluding that the browser's timezone is the issue here?

My second question is how this actually happens, or more importantly how the user can correct this. The offending browser is Chrome 81 for Android, and as far as I can tell there's no way to view or change the timezone; it's just set automatically using the system settings (yet the clock for this device is actually set correctly).

Finally, since all the users are in the same timezone, just hard coding the app to display correctly for the specified timezone is also an option. Do Angular date pipes provide a way to do this? Ideally, this would accommodate Daylight Savings, so that this doesn't break again in the spring.

Time zones are a special circle of hell. If you have the option to, never use native js Dates anywhere and use a library like Luxon. If you can’t, and you are 100% sure the users are all in the same time zone, look into using the toLocale[Date | Time]String methods on Date where you can set the timeZone option to force it to render in a given zone that should handle DST and all that fun stuff. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

prom candy
Dec 16, 2005

Only I may dance

Tei posted:

I find the => operator ugly

I like you Tei but your takes today are absolutely wild

AlphaKeny1
Feb 17, 2006

Lumpy posted:

Time zones are a special circle of hell. If you have the option to, never use native js Dates anywhere and use a library like Luxon. If you can’t, and you are 100% sure the users are all in the same time zone, look into using the toLocale[Date | Time]String methods on Date where you can set the timeZone option to force it to render in a given zone that should handle DST and all that fun stuff. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Yeah this 100% use something else if you can. I've had much better success with moment.js.

Otherwise you'll have to figure some workaround with the javascript Date api. Like force it to read in UTC and convert or something.

Ima Computer
Oct 28, 2007

Stop all the downloading!

Help computer.

Tei posted:

I find the => operator ugly
Have you tried any fonts with programming ligatures, like FiraCode or Hasklig?

Tei
Feb 19, 2011
Probation
Can't post for 4 days!

prom candy posted:

I like you Tei but your takes today are absolutely wild

I have a lot of bad opinions. I hope you still like me despite them :D

I programmed with Perl and like terse code, but => is a bit too much. I also like "{" and "}" and is why I don't like Python much.

Is just a aesthetic preference, nothing mayor. I want my code a bit more verbose and not too much based on mystery symbols.

Data Graham
Dec 28, 2009

📈📊🍪😋



fireraiser posted:

Have you tried any fonts with programming ligatures, like FiraCode or Hasklig?

Oh poo poo is that what those websites demonstrating these kinds of operators are doing.

I’m like reading a thing that says “yeah just use a 📎 b” and thinking well that’s going to present some problems

prom candy
Dec 16, 2005

Only I may dance

Tei posted:

I have a lot of bad opinions. I hope you still like me despite them :D

I programmed with Perl and like terse code, but => is a bit too much. I also like "{" and "}" and is why I don't like Python much.

Is just a aesthetic preference, nothing mayor. I want my code a bit more verbose and not too much based on mystery symbols.

I just find it so much easier to type, especially for inline anonymous functions.

code:
arr.map(function(item) {
  return item.property
})

arr.map(item => item.property)

Impotence
Nov 8, 2010
Lipstick Apathy
You can always set up eslint to demand (alwaysparens) => { return alwaysbraces }, and make it --fixable

prom candy
Dec 16, 2005

Only I may dance
Forcing no implicit return would be getting rid of one of the nicest features of ES6 though

Ruggan
Feb 20, 2007
WHAT THAT SMELL LIKE?!


prom candy posted:

I like you Tei but your takes today are absolutely wild

haha word

I love =>

Chenghiz
Feb 14, 2007

WHITE WHALE
HOLY GRAIL

New Coke posted:

I've been maintaining an Angular app that allows employees to clock in via a web portal, and some of them are seeing the time appear incorrectly. First off, I've added a bit of logging to try to get some visibility into the problem and confirm my suspicion; that some of their browsers are using an incorrect timezone.

My first question, just so that I know I'm on the right track, is whether or not this line of code is telling me what I think it is:

code:
new Date().getTimezoneOffset()
I know what this should be, given my location, and based on the logging I've implemented, the user that has been experiencing this does get a different result for this. Am I correct in concluding that the browser's timezone is the issue here?

My second question is how this actually happens, or more importantly how the user can correct this. The offending browser is Chrome 81 for Android, and as far as I can tell there's no way to view or change the timezone; it's just set automatically using the system settings (yet the clock for this device is actually set correctly).

Finally, since all the users are in the same timezone, just hard coding the app to display correctly for the specified timezone is also an option. Do Angular date pipes provide a way to do this? Ideally, this would accommodate Daylight Savings, so that this doesn't break again in the spring.

You should be handling all this time stuff on the server side. Never trust the client. Make an endpoint that the client posts to that simply indicates the user clocked in. Get the time on the server when the request comes in and store it in your database in UTC. When you display that time to a user, send it to the client in UTC and use the client time zone to translate it, at which point the previous suggestions about luxon and moment become relevant.

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Chenghiz posted:

You should be handling all this time stuff on the server side. Never trust the client. Make an endpoint that the client posts to that simply indicates the user clocked in. Get the time on the server when the request comes in and store it in your database in UTC. When you display that time to a user, send it to the client in UTC and use the client time zone to translate it, at which point the previous suggestions about luxon and moment become relevant.

Just an FYI, moment is no longer being supported in favor of Luxon. Just in case that helps anyone looking at libraries for the first time. First time, get it!

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply