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
Sad Panda
Sep 22, 2004

I'm a Sad Panda.
I'm using eslint-config-airbnb-base. In my code I have optional chaining to deal with a possible querySelector not existing.

JavaScript code:
        function getStatus(record) {
          return (
		return record.querySelector('.product-mark')?.innerText || null          );
        }
It works fine but eslint says 'Parsing error: Unexpected token .'


https://stackoverflow.com/questions/61628947/eslint-optional-chaining-error-with-vscode this mentions about using eslint of 7.5 or higher but my npm list is...

code:
@google-cloud/functions-framework@3.3.0
 crypto@1.0.1
 env-cmd@10.1.0
 eslint-config-airbnb-base@15.0.0
 eslint-plugin-import@2.29.0
 eslint@8.53.0
 express@4.18.2
 md5@2.3.0
 mongodb@5.9.1
 puppeteer@19.11.1
If there's a better way to write that code, I'll also take that advice! I'm rather new to this. It seemed like an 'elegant' way to do it in an easy to understand line instead of having to do eg...

JavaScript code:
function getStatus(record) {
   const status = record.querySelector('.product-mark');
   return status ? status.innerText : null;
}

Sad Panda fucked around with this message at 16:53 on Nov 4, 2023

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice
JavaScript code:
return record?.querySelector('.product-mark')?.innerText ?? null;
\/\/ Oh duh, I did not answer the actual question.

Lumpy fucked around with this message at 23:45 on Nov 5, 2023

Doom Mathematic
Sep 2, 2008
You probably don't have ESLint configured to understand the optional chaining operator, ?.. Take a look at your ESLint configuration, and make sure you have the parserOptions.ecmaVersion option configured to a version of ECMAScript which actually had that operator. The default value is ES5, which did not. In fact, it's probably best to just put 'latest' here.

Lumpy posted:

JavaScript code:
return record?.querySelector('.product-mark')?.innerText ?? null;

Note that if ESLint doesn't recognise ?. it's not going to recognise ?? either. Also, you need to work out what the correct behavior is if innerText is an empty string. Should your code return the empty string? Then you can use ??. Should it return null instead? Then you should use ||.

Doom Mathematic fucked around with this message at 22:25 on Nov 5, 2023

Sad Panda
Sep 22, 2004

I'm a Sad Panda.

Doom Mathematic posted:

You probably don't have ESLint configured to understand the optional chaining operator, ?.. Take a look at your ESLint configuration, and make sure you have the parserOptions.ecmaVersion option configured to a version of ECMAScript which actually had that operator. The default value is ES5, which did not. In fact, it's probably best to just put 'latest' here.

Note that if ESLint doesn't recognise ?. it's not going to recognise ?? either. Also, you need to work out what the correct behavior is if innerText is an empty string. Should your code return the empty string? Then you can use ??. Should it return null instead? Then you should use ||.

Thanks - that was it. ESlint, prettier & airbnb config were all arguing with each other. Now got that setup - thank you.

Trying to make that happy is another fun thing. For example, ESLint says no for of loops & no await in loops. This breaks both of them.

JavaScript code:
  for (const [index, URLToScrape] of URLsToScrape.entries()) {
    console.log(`Scraping URL ${index}/${URLsToScrape.length}: ${URLToScrape}`);
    await page.goto(URLToScrape, {
      waitUntil: 'domcontentloaded',
    });
    more logic
}
For me that's just fine. I use for of because I want to iterate through a list of 3000 URLs that I've scraped and want them to do it one after another. It uses one page object (a puppeteer.launch.newPage()) and makes its way through that list.

Am I being wrong in ignoring ESLint for that? https://eslint.org/docs/latest/rules/no-await-in-loop the 'when not to use it' part at the bottom of this seems to suggest my case makes sense.

prom candy
Dec 16, 2005

Only I may dance

Sad Panda posted:

I'm using eslint-config-airbnb-base.

Found your problem

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Doom Mathematic posted:

Should your code return the empty string? Then you can use ??. Should it return null instead? Then you should use ||.

What's your reasoning here?

My opinion is that if you have a default value, always use ?? and only use || if you're dealing with boolean logic.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
For ages I used || for defaults, going through old code I always change it to ??.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

Nolgthorn posted:

For ages I used || for defaults, going through old code I always change it to ??.

Yeah, same.

some kinda jackal
Feb 25, 2003

 
 
Can someone explain to me, as you would a child, what a Tuple is good for? I think this is a failure of imagination because every tutorial or video I’ve seen I kind of feel like I, throwing around my entire two weeks of non-real-world programming experience, would probably use something else. One thing I see cited a lot is if I want to return multiple things from a function, at which point I instinctively just want to declare a type and have my func return that type. I guess if I don’t know exactly what I’m returning? Or is this one of those “there are eight different ways to do everything, just use whatever fits your style” type of situation?

100% a failure of imagination, yeah.

teen phone cutie
Jun 18, 2012

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

some kinda jackal posted:

Can someone explain to me, as you would a child, what a Tuple is good for? I think this is a failure of imagination because every tutorial or video I’ve seen I kind of feel like I, throwing around my entire two weeks of non-real-world programming experience, would probably use something else. One thing I see cited a lot is if I want to return multiple things from a function, at which point I instinctively just want to declare a type and have my func return that type. I guess if I don’t know exactly what I’m returning? Or is this one of those “there are eight different ways to do everything, just use whatever fits your style” type of situation?

100% a failure of imagination, yeah.

an example of something I just did at work:

I have an autocomlete input where I want to bold the text that matches the user input, so

user input: "Jer"

TypeScript code:
const getMatchedInput = (userInput: string, textToCheckAgainst: string=): [string, string, string] =>  {
  return [beforeText, matchedText, afterText]
}

getMatchedInput("Jer", "New Jersey") // ["New ", "Jer", "sey"] - bold array index 1 always
getMatchedInput("", "New Jersey") // ["New ", "", "Jersey"]

teen phone cutie fucked around with this message at 00:05 on Nov 9, 2023

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.

some kinda jackal posted:

Can someone explain to me, as you would a child, what a Tuple is good for? I think this is a failure of imagination because every tutorial or video I’ve seen I kind of feel like I, throwing around my entire two weeks of non-real-world programming experience, would probably use something else. One thing I see cited a lot is if I want to return multiple things from a function, at which point I instinctively just want to declare a type and have my func return that type. I guess if I don’t know exactly what I’m returning? Or is this one of those “there are eight different ways to do everything, just use whatever fits your style” type of situation?

100% a failure of imagination, yeah.

Tuple is for lazy people who don't want to make a special return value class.

some kinda jackal
Feb 25, 2003

 
 

Bruegels Fuckbooks posted:

Tuple is for lazy people who don't want to make a special return value class.

If I'm being honest, I did come in here almost asking just that. I'm glad someone explained it to me though.

teen phone cutie posted:

an example of something I just did at work:

I have an autocomlete input where I want to bold the text that matches the user input, so

user input: "Jer"

TypeScript code:
const getMatchedInput = (userInput: string): [string, string, string] =>  {
  return [beforeText, matchedText, afterText]
}

getMatchedInput("Jer") // ["New ", "Jer", "sey"] - bold array index 1 always

Ok this one I follow. I guess the value prop here vs an Array is that you've got a fixed set rather just having to remember how many members you're returning in an array?

So yeah, I guess this WAS a failure of imagination. In the above I guess it would probably be overkill to create a type/interface for the retval vs just passing everything in a contained tuple (opposed to an array).

Thanks!

some kinda jackal fucked around with this message at 00:04 on Nov 9, 2023

Polio Vax Scene
Apr 5, 2009



tuples were a mistake

teen phone cutie
Jun 18, 2012

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

some kinda jackal posted:

If I'm being honest, I did come in here almost asking just that. I'm glad someone explained it to me though.

Ok this one I follow. I guess the value prop here vs an Array is that you've got a fixed set rather just having to remember how many members you're returning in an array?

So yeah, I guess this WAS a failure of imagination. In the above I guess it would probably be overkill to create a type/interface for the retval vs just passing everything in a contained tuple (opposed to an array).

Thanks!

yeah idk. Tuples very rarely have a use-case I feel like. Use whatever works :shrug:

also I updated that example because I'm just now realizing it makes no sense lol

Doom Mathematic
Sep 2, 2008

Wheany posted:

What's your reasoning here?

My opinion is that if you have a default value, always use ?? and only use || if you're dealing with boolean logic.

That's a reasonable rule of thumb in most cases. But the question is when you want to drop through to that default value. The original code was:

Sad Panda posted:

JavaScript code:
        function getStatus(record) {
          return (
		return record.querySelector('.product-mark')?.innerText || null          );
        }

So in this case, what we're actually asking is, when should we return innerText, and when should we give up and instead return the default value, null?

In particular in this case, what happens if innerText works out to be the empty string, ''?

  • If we write || null, as we currently have here, then we'll drop through to the default value and return null instead.
  • If, as you suggest, we write ?? null instead, then we'll return the empty string.

I think the first of these is probably the correct behavior. In the second case, we have a getStatus which sometimes returns the empty string, and sometimes returns null. That's two different falsy values which we might need to check for. If other code is using ?? then the empty string could propagate a long way before something actually catches it and realises that this isn't a valid status.

Unless the empty string is a valid status! Which I don't actually know. So I gave OP the option.

some kinda jackal
Feb 25, 2003

 
 
What I think I remember from getters/setters in C# from 200 years ago, I could use the same name for the getter/setter accessors as the property they're manipulating. Doesn't seem like that's possible in TS/JS unless I'm missing something. So I guess maybe I'm going to ask more of a general coding practice/pattern question but with a typescript lens:

If I have something like

TypeScript code:
class Person {
	firstName: string;
	lastName: string;
	age: number;
	email: string;

	constructor() { all the things };
}
but I wanted to manipulate the name properties at assignment time, is the right approach to make the properties private with some sort of name distinction, then make get/set accessors for firstname lastname? Something like

TypeScript code:
class Person {
	private _firstName: string;
	private _lastName: string;
	age: number;
	email: string;

	constructor() { all the things };
	
	set firstName(value: string): void {
		this._firstName = value.toUpperCase();
	}
	get firstName(): string { return this._firstName; };

	set/get lastName(same same) {};

}
Is this generally how it's done? Sorry if I butchered the accessor syntax, I'm doing this from memory without a long history but I think you know what I mean.

I was about to comment that I don't love the idea of having to remember which property I made private with an underscore, but then I remembered that presumably I'm creating these accessors because all modification to the properties should be done consistently so I wouldn't really need to remember and I should still use this.firstName rather than manipulating _firstName unless I have a specific need to.

Sorry I think you guys are dealing with some basic beginner questions but I'm thankful that you've all been gracious about it so far. If you think this is better suited for the beginner questions thread I'm happy to vamoose.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope
Yeah actually I did create a function just today that returns Number(value) || 0, just in case Number(value) evaluates to NaN

Wheany fucked around with this message at 06:37 on Nov 11, 2023

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

some kinda jackal posted:

but I wanted to manipulate the name properties at assignment time, is the right approach to make the properties private with some sort of name distinction, then make get/set accessors for firstname lastname? Something like

To make a property private, prepend its name with a # character:

JavaScript code:
class Person {
	#name = '';
	get name() {
		return this.#name;
	}
	set name(n) {
		this.#name = n;
	}

}

some kinda jackal
Feb 25, 2003

 
 
Is that a style thing or an actual typescript syntax thing because it’s not giving me any errors on private, but for all I know I could be doing something unintended..

Switching to the hash anyway, thanks!

Jazerus
May 24, 2011


some kinda jackal posted:

What I think I remember from getters/setters in C# from 200 years ago, I could use the same name for the getter/setter accessors as the property they're manipulating. Doesn't seem like that's possible in TS/JS unless I'm missing something. So I guess maybe I'm going to ask more of a general coding practice/pattern question but with a typescript lens:

you can run objects through a Proxy wrapper to get the semantics you want, where property access defers to the getter and setter making it impossible to actually touch the values directly unless you go out of your way to pull a reference to the original pre-proxy object. there is probably a library that sets the wrapper up for you but conceptually it's pretty simple to roll your own, if a bit tedious

necrotic
Aug 2, 2005
I owe my brother big time for this!

some kinda jackal posted:

Is that a style thing or an actual typescript syntax thing because it’s not giving me any errors on private, but for all I know I could be doing something unintended..

Switching to the hash anyway, thanks!

The hash syntax for private fields is pure JavaScript, and actually makes the field privately scoped. Typescript has an actual private keyword that only makes it private _to typescript_, the field is still fully “public” in JavaScript.

Wheany
Mar 17, 2006

Spinyahahahahahahahahahahahaha!

Doctor Rope

some kinda jackal posted:

Is that a style thing or an actual typescript syntax thing because it’s not giving me any errors on private, but for all I know I could be doing something unintended..

Switching to the hash anyway, thanks!

quote:

» class Person {
#name = '';
get name() {
return this.#name;
}
set name(n) {
this.#name = n;
}

}
← undefined
» const p = new Person()
← undefined
» p.name='QQQ'
← "QQQ"
» p.#name
← Uncaught SyntaxError: reference to undeclared private field or method #name debugger eval code:1:3
it's actually private

Rob Filter
Jan 19, 2009
How do you profile javascript code? Sampling seems straightforward, but I'm not sure how to do instrumental / structural profiling. Are there libraries that let you do things similarly to QueryPerformanceCounter windows stuff?

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.

Rob Filter posted:

How do you profile javascript code? Sampling seems straightforward, but I'm not sure how to do instrumental / structural profiling. Are there libraries that let you do things similarly to QueryPerformanceCounter windows stuff?

the libraries that do it right are just using performance.mark() and performance.measure() https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark.

If you just need a current high resolution timestamp you can do performance.now().

Performance api in js is closest thing to QueryPerformanceCounter.

Rob Filter
Jan 19, 2009

Bruegels Fuckbooks posted:

the libraries that do it right are just using performance.mark() and performance.measure() https://developer.mozilla.org/en-US/docs/Web/API/Performance/mark.

If you just need a current high resolution timestamp you can do performance.now().

Performance api in js is closest thing to QueryPerformanceCounter.

Cheers!

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I like storing datetimes as integers in the database. For a while now I've been stripping ms off the unix timestamp so that it fits, but this is just pushing back the problem until unsigned integers can't store the number of seconds since epoch. So now in order to continue feeding my delusion I want to start stripping years off the integer too. So It'd be seconds since epoch plus 50 years.

That ought to fit more numbers in there for a little bit longer.

The suggestion would be stop using an unsigned integer use a bigint or something like that. Sure but then what once I try and read the number in JavaScript, I don't want to deal with a BigInt in JavaScript.

Jabor
Jul 16, 2010

#1 Loser at SpaceChem
Why not just use a 64-bit number in your database instead of loving around with manual conversions? Even with only the 53 bits of precision that you can get when converting that to a JS Number, that should be plenty to cover you for millions of years.

Or how about your database's native datetime type?

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
MySQL Int for example stores up to 2,147,483,647 which is in 2038 sometime. My app then becomes one of many that will break on that date so I'm expected to store a unix timestamp as BigInt instead. Javascript can work with numbers up to 9,007,199,254,740,991 which is in 2255 sometime so that leaves a lot of room. I guess the difficulty is in converting the database's BigInt to a javascript number.

For some reason if I use BigInt my ORM refuses to return anything but a javascript BigInt which then requires conversion. It's Prisma, by the way, the best ORM of all time, except for this one dire flaw.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Yes I know the correct answer is to use a datetime format. I just also don't like working with Date objects.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I have decided to use datetime, copilot convinced me in like 30 minutes.

Data Graham
Dec 28, 2009

📈📊🍪😋



Oh so you believe a robot but not goons

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I am argumentative and after years of experience I've found I prefer getting into confrontations with robots.

Combat Pretzel
Jun 23, 2004

No, seriously... what kurds?!
Temporal! stat!

What’s the hold up now, anyway? Before it was the IETF dragging their balls across crushed glass in regards to defining timezone codes. But that’s done for a while now. Please kill the Date class finally.

Polio Vax Scene
Apr 5, 2009



its probably been so widely used now that changing it in any way would cause chaos

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense

Polio Vax Scene posted:

its probably been so widely used now that changing it in any way would cause chaos

Deprecate, lets get this ball rolling

Roadie
Jun 30, 2013
I really want some kind of final Temporal implementation I can use without dragging in like 40kb of unoptimized extra stuff.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I think it's odd that Temporal defaults to using timezones, specifically the system timezone, unless you clarify otherwise with the much longer "Plain" naming convention. It's like we're gonna stick with that, even though the only time I can ever see timezones being useful is when we want to display some data to a user and even then the system timezone isn't what we would use.

Seems like if you created a Temporal object using a string that contains a timezone it should assume you want that time and date in utc. Or assume that any datetime you provide without one is otherwise in utc.

Nolgthorn fucked around with this message at 11:14 on Dec 12, 2023

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Roadie posted:

I really want some kind of final Temporal implementation I can use without dragging in like 40kb of unoptimized extra stuff.

Meh, on the front end you just compress the giant background image marketing _has_ to have on the login screen by an extra 1% and you save the file size of Luxon in your bundle.

roomforthetuna
Mar 22, 2005

I don't need to know anything about virii! My CUSTOM PROGRAM keeps me protected! It's not like they'll try to come in through the Internet or something!

Lumpy posted:

Meh, on the front end you just compress the giant background image marketing _has_ to have on the login screen by an extra 1% and you save the file size of Luxon in your bundle.
But that's how marketing excuses their giant image, because if you just compress the humungous machine learning model that the telemetrics team wants in there you save the file size of their giant image. Where will it end?!

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

roomforthetuna posted:

But that's how marketing excuses their giant image, because if you just compress the humungous machine learning model that the telemetrics team wants in there you save the file size of their giant image. Where will it end?!

I mean, if we keep doing it, eventually nobody will have to download anything, right?

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