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
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.

Skyarb posted:

I am still confused, I am sorry. What are string literal types? I thought a type could only be a string?

A string literal in typescript is a subtype of string - e.g. "hello world" is considered a string subtype. You can use this have type checker ensure only certain strings can be passed as a parameter.

e.g.
code:
 type Foo = "butt" | "head";

class UIElement {
  animate(foo: Foo) {
    if (foo === "butt") {
      // ...
    } else if (foo === "head") {   
     // ...
    } 
  }
}

Adbot
ADBOT LOVES YOU

redreader
Nov 2, 2009

I am the coolest person ever with my pirate chalice. Seriously.

Dinosaur Gum
I'm interviewing for jobs currently, and I was working in typescript for the last year (doing API testing using jest, since I'm in QA). This was my introduction to typescript/ javascript. At my job people referred to javascript and typescript interchangeably. I've read a couple of explainers but still unsure about how to go about this whole thing. I see lots of 'javascript: node.js' jobs around. I read that node.js is not compatible with typescript. I'm interviewing for a javascript node job tomorrow, lol. I don't expect to get it but interviews are practice for interviews.

Now I have to figure out what I know that is typescript and what is javascript, and do some javascript basic tutorials and maybe also do some node.js exercises or something. I'm pretty confused! Base Javascript tutorials seem very 'here's how to make a website!' but I've been making backend scripts using typescript and am more interested in doing something like, using jest in normal javascript to make an API test.

note, I'm new to javascript but not coding. My experience is in ruby, scala, java, c++, php, perl, python, typescript. Another note is I'm annoyed that literally every job I've ever had has made me use a different language, so now I know a lot of them but none of them 'like the back of my hand'. Even javascript, that I've been using the last year or so, is, as you can see, ??? to me. (Maybe I should be saying I know typescript rather than javascript. I don't even know!)

On another note, is there any recommended starter tutorial page or something for 'javascript'? googling finds me a bunch of ones but not sure which ones are good.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Typescript is javascript with a type system added. It all works the same, just sans types.

It won't run without being compiled to javascript, which is where the "it won't run on node" comes from.

redreader
Nov 2, 2009

I am the coolest person ever with my pirate chalice. Seriously.

Dinosaur Gum
You're going to laugh and laugh, but I just reversed a string in javascript and it was exactly the same as typescript. So lol, phew. Time to do some more basic-rear end exercises but that's the #1 interview screening question in my experience.

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer

redreader posted:

You're going to laugh and laugh, but I just reversed a string in javascript and it was exactly the same as typescript. So lol, phew. Time to do some more basic-rear end exercises but that's the #1 interview screening question in my experience.

Typescript is literally a superset of ES6. They only added type stuff. Don't worry about it. Use babel to transpile to whatever javascript version your platform supports and you're good.

Doom Mathematic
Sep 2, 2008
The confusing part is that in front-end development, it's very common to take high-level JavaScript, which uses modern ES6+ syntax, and compile it down to lower-level JavaScript (~ES5) for consumption by the web browser. In this context, TypeScript can be considered as another dialect of high-level JavaScript. So, switching from JavaScript to TypeScript in the front end is usually relatively "simple", you add a different preset to your compiler, configure it properly, and proceed as before.

Whereas, with backend Node.js, the JavaScript you write is typically directly interpreted by Node.js. There is no compilation step here, typically. And Node.js does not natively comprehend TypeScript. Which means, to switch from JavaScript to TypeScript in the backend, you have to introduce this whole new compilation step which wasn't there before.

Roadie
Jun 30, 2013
Typescript is Javascript, plus type annotations and definitions, plus a tiny handful of specific differences they're specifically trying to avoid doing more of now like enums and old decorators.

redreader
Nov 2, 2009

I am the coolest person ever with my pirate chalice. Seriously.

Dinosaur Gum
Please bear with me, as previously I've used javascript repos that already exist and added code to them, but never done the setup myself. It seems with javascript there's a lot of extra stuff that I don't really understand yet, like 'how to decide what goes into package.json'. For instance in my code I write, I can say "x=5" and it works, but in the tech screen I did that and it showed an error, and the guy interviewing me added 'let' in front and it worked. Why is my environment ok with that but the coderpad environment wasn't?

I'm trying to use not-typescript javascript but having a bit of trouble. So I got npm and vscode to write code with and that works. I got jest using npm and writing a super basic test works. But I tried to make a file libraryfile.js with exported functions in it, then import (or require, I tried both) the functions in the libraryfile.test.js file, and for the love of god I cannot import the files. I saw stuff saying you need to add
"type": "module",

to your package.json to get that to work, but that doesn't work. I'll formulate my problem better tomorrow. If anyone can point at a best definitive way to import/require files (I suppose since the job is for node.js I should learn that method), I'd appreciate it. I'd post an error I get but I've tried like 5 things and got 5 different error messages.

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.

redreader posted:

For instance in my code I write, I can say "x=5" and it works, but in the tech screen I did that and it showed an error, and the guy interviewing me added 'let' in front and it worked. Why is my environment ok with that but the coderpad environment wasn't?

x=5 declares the variable in global scope. the coderpad environment probably is set to "use strict" which disallows assigning a variable in global scope. assigning a variable in global scope is bad because there's the possibility of name collisions (e.g what if there are multiple scripts that use x?). "let" declares a variable in block scope (e.g. the value of x would only be accessible in the block where let x = whatever is used.) You'd be surprised how many really annoying bugs using "let" instead of assigning global or using "var" will catch.

i'd suggest reading a recent book on js though, the above is a pretty basic thing you should know as a js developer.

redreader
Nov 2, 2009

I am the coolest person ever with my pirate chalice. Seriously.

Dinosaur Gum

Bruegels Fuckbooks posted:

x=5 declares the variable in global scope. the coderpad environment probably is set to "use strict" which disallows assigning a variable in global scope. assigning a variable in global scope is bad because there's the possibility of name collisions (e.g what if there are multiple scripts that use x?). "let" declares a variable in block scope (e.g. the value of x would only be accessible in the block where let x = whatever is used.) You'd be surprised how many really annoying bugs using "let" instead of assigning global or using "var" will catch.

i'd suggest reading a recent book on js though, the above is a pretty basic thing you should know as a js developer.

Thanks!

barkbell
Apr 14, 2006

woof

https://eloquentjavascript.net/

redreader
Nov 2, 2009

I am the coolest person ever with my pirate chalice. Seriously.

Dinosaur Gum

YESSS! THANKS! That post by Bruegels Fuckbooks made me realise I have a lot of learning ahead before monday.

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender
java script: The Good Parts used to be the bible, but I think it's pretty out of date now. Another resource that was introduced recently is https://javascript.info/ which covers all the modern features of JS, and how they relate to web dev.

RadiRoot
Feb 3, 2007
recently learned this newish js feature which is surprisingly cool. had an issue with calculating font sizes and it worked really well.

https://web.dev/resize-observer/

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I have a email inbox type of application. I'm storing the txt and the html versions of incoming emails in two text fields in the database. I'm also storing file attachments.

What I'm trying to do is determine the approximate size of the emails. I've got the attachment size figured out. What is the best way to determine the size of the rest?

Is it as simple as counting the number of characters and multiplying it to determine approximate size? What is that multiple? I think I'm storing utf-8 formatted text.

The subject of the messages is stored as varchar. Does that take up the same amount of space as the text fields? That is, based on the number of characters? Is it even worth calculating?

None of this has to be particularly precise.

sterster
Jun 19, 2006
nothing
Fun Shoe
Does this get what you need? https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder

Or this? https://stackoverflow.com/a/23329386

sterster fucked around with this message at 20:24 on Dec 11, 2020

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I think I know

After coming up with a better way to word a google search I've found that text fields are 1 byte per character plus a 2 byte overhead.

I should be able to work with that. Sorry for the useless and wordy question above. Stop me if you think I'm doing something wrong. Thank you

kiwid
Sep 30, 2013

I'm looking for a library that allows me to drag simple shapes (circle, rectangle, etc.) with text in them and when a user drags the shape it saves the position so it doesn't reset on page reload. I have no idea how to better describe this other than I'm essentially looking to do this: https://drawsql.app/templates/koel but in a more simple fashion.

Can anyone point me in the right direction?

edit: I may have found what I was looking for here: https://interactjs.io/

kiwid fucked around with this message at 17:30 on Dec 14, 2020

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Quick question for you goons; I'm using node-postgres to access a database. My query script looks like this:

code:
async.parallel(
    {
      company: function (callback) {
        pool.query(
          "SELECT * FROM company WHERE id = $1",
          [req.params.id],
          callback
        );
      },
    },
    function (err, results) {
      if (err) {
        next(err);
      }
      console.log(results.company.rows)
      res.render("companypage", { companylist: results.company.rows });
    }
This works and gets me the results I want through results.company.rows, except the result comes in the form of a array of just one company (obviously). This means that in PUG I have to call information like this:

companylist[0].company_name

Is there a way to destructure (is that the right word?) to get rid of the [0] part of calling the information in pug? I feel like this is something easy but im just overlooking it.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
const [ foundCompany ] = companyList

if (foundCompany) { }

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Thanks; although I'm confused why that works. Does turning it into a array automatically un-jsonify the result?

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!

Empress Brosephine posted:

Thanks; although I'm confused why that works. Does turning it into a array automatically un-jsonify the result?
It's not turning it into an array, it's a destructuring assignment operation.

Like if you had an array x = [1, 2, 3] then you can do const [a, b, c] = x, after which a=1, b=2 and c=3. It just looks a bit less clear in this case because you're doing it with just one element.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
Oh yeah duh forgot about that. Thanks for the help and the link!

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
hi friendly goons I have a simple question about package.json that I am stumped over because I'm a idiot.


I'm using bulimia for my css and I use the npm version of it, so I need to build it and watch it. At the same time I'd like to use nodemon to watch changes, but I can't seem to figure out how to set my scripts portion of package.json right so that I can hit nodemon into the terminal and just have it work :( can anyone help guide?

code:
"scripts": {
    "css-build": "node-sass --omit-source-map-url sass/mystyles.scss public/stylesheets/mystyles.css",
    "css-watch": "npm run css-build -- --watch",
    "watch-code": "nodemon ./bin/www",
    "start": "npm run watch-code & npm run css-watch"
is what I have right now. I feel like I'm missing something to it that would actually utilize nodemon and watch the code

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
so your html file(s) are referencing the built css and you want the page to refresh when you make changes to the built css files along with any non-built html/js?

i’m assuming your problem here is that the css command is never finishing. if you

some-command && some-other-command

the right command never executes if the left command is in watch mode and doesn’t technically finish.

as a quick fix, i’d recommend concurrently to run commands in parallel:

https://www.npmjs.com/package/concurrently

but this might be the point where you might want to transition to something like webpack, but i’m not exactly sure of your use-case here.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
yeah, although I don't really ever make css changes so I guess I don't have to have that as an option. I didn't know about the right command though, I was just blindly following https://bulma.io/documentation/customize/with-node-sass/ lol.

does webpack work with expressjs? This is only a temporary issue I guess, since nodemon obviously won't be live on the actual server (although I guess web pack would replace nodemon)

Sorry for so many questions

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
ah yeah didn't realize you were using express. A quick google search says it should be possible to get what you're looking for:

https://dev.to/riversun/how-to-run-webpack-dev-server-on-express-5ei9

https://bulma.io/documentation/customize/with-webpack/

so webpack is a tool responsible for bundling your JavaScript files into one (or many) minified JS files.

and if you use that with webpack-dev-server (which is responsible for running webpack PLUS hot-reloading on file change) and the sass-loader plugin for webpack, you should be able to get what you want with one command like

JavaScript code:
{
  "watch-code": "webpack-dev-server"
}
It's a lot to digest, but build tools like webpack are pretty common-place with JavaScript and you'll see it used a lot in production apps.

People usually use webpack (along with plugins like MiniCssExtractPlugin, Babel, webpack-dev-server, etc) to do things like:

1. Minify CSS
2. Inject minified CSS into an html file automatically
3. Transpile JavaScript from ES6 syntax down to ES5 syntax, so it can be parsed by legacy browsers (which is probably less important with server-side JS)
4. Hot reload file changes
5. Minify/bundle JavaScript.

teen phone cutie
Jun 18, 2012

last year i rewrote something awful from scratch because i hate myself
but also another valid approach might be separating the watching of your client-side code from your server-side code and running the commands in two separate terminals, which would make a lot of what I said moot.

Empress Brosephine
Mar 31, 2012

by Jeffrey of YOSPOS
That is so awesome thanks so much. I also didn't think about running them in two seperate windows which would be the easy way lol

Chas McGill
Oct 29, 2010

loves Fat Philippe
Any recommendations for a react rich text editor that can export to markdown? Currently looking at Draftail.

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer

Chas McGill posted:

Any recommendations for a react rich text editor that can export to markdown? Currently looking at Draftail.

We've been happy enough with this one https://github.com/jpuri/react-draft-wysiwyg. Looks like both are built on top of draftjs either way.

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
Is there a place I can post my vanilla JS code and get suggestions on how to do it better? I don't know if there's an automated tool or I could post my embarrassing code here or somewhere else and get advice. I have a lot of Javascript that I put together on my own that works, but I know isn't done as efficiently as possible. I spent a few hours yesterday putting together an endless carousel that uses flexbox ordering, for example, so it's all in-browser DOM manipulation stuff.

teen phone cutie
Jun 18, 2012

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

LifeLynx posted:

Is there a place I can post my vanilla JS code and get suggestions on how to do it better? I don't know if there's an automated tool or I could post my embarrassing code here or somewhere else and get advice. I have a lot of Javascript that I put together on my own that works, but I know isn't done as efficiently as possible. I spent a few hours yesterday putting together an endless carousel that uses flexbox ordering, for example, so it's all in-browser DOM manipulation stuff.

:justpost:

Chas McGill
Oct 29, 2010

loves Fat Philippe

Osmosisch posted:

We've been happy enough with this one https://github.com/jpuri/react-draft-wysiwyg. Looks like both are built on top of draftjs either way.

Thanks, I ended up using Slate (which may be overkill) and I'm impressed so far. I'll check that one out if I run into problems though.

LifeLynx
Feb 27, 2001

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

Alright, here it is: https://codepen.io/LyfeLynx/pen/ExgdmoM

It seems to work well. The only problem I have is that the order keeps going up and up. It assigns every item an order number at the start, and keeps incrementing the flex order by 1 every two seconds. The easiest thing I can think of is to periodically reset it by fading the carousel out, say if the flex order reaches 3000 because no one's looking at this for six minutes, doing the prepareCarousel, and then fading back in.

smackfu
Jun 7, 2004

Was thinking it would be neat to just have a window with a JavaScript console running all the time, rather than opening Chrome dev tools. Does that exist?

I guess a terminal running node would do the job actually.

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.

smackfu posted:

Was thinking it would be neat to just have a window with a JavaScript console running all the time, rather than opening Chrome dev tools. Does that exist?

I guess a terminal running node would do the job actually.

There's a web interface for the chrome debugger. https://chromedevtools.github.io/devtools-protocol/#remote. If you start chrome with the debugger port enabled, it can make it much easier to just have another browser window open to the page (perhaps even on another computer). This can help if you're debugging something annoying in web ui.

Osmosisch
Sep 9, 2007

I shall make everyone look like me! Then when they trick each other, they will say "oh that Coyote, he is the smartest one, he can even trick the great Coyote."



Grimey Drawer

LifeLynx posted:

Alright, here it is: https://codepen.io/LyfeLynx/pen/ExgdmoM

It seems to work well. The only problem I have is that the order keeps going up and up. It assigns every item an order number at the start, and keeps incrementing the flex order by 1 every two seconds. The easiest thing I can think of is to periodically reset it by fading the carousel out, say if the flex order reaches 3000 because no one's looking at this for six minutes, doing the prepareCarousel, and then fading back in.

I think it's perfectly functional, but I'd definitely prefer coding and writing a different style where for example the images are not already hardcoded in the html but added from data in code, and where there's fewer globals. I definitely would rather be taking the head off the list of images and adding it to the tail rather than doing index math for example.

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

LifeLynx posted:

Alright, here it is: https://codepen.io/LyfeLynx/pen/ExgdmoM

It seems to work well. The only problem I have is that the order keeps going up and up. It assigns every item an order number at the start, and keeps incrementing the flex order by 1 every two seconds. The easiest thing I can think of is to periodically reset it by fading the carousel out, say if the flex order reaches 3000 because no one's looking at this for six minutes, doing the prepareCarousel, and then fading back in.

You call scrollCarousel(); in this loop
code:
	carItems.forEach(function(carItem) {
		carItem.width = carWidth/numSlides;
		carItem.style.order = carIndex;
		carItem.style.marginLeft = 0;
		carItem.style.opacity = 0.5;
		scrollCarousel();
	});
But I don't think you actually want to? You start the actual loop down here
code:
setInterval(scrollCarousel, animSpeed);
Also, you have this line in scrollCarousel:
code:
if (currentTarget > document.querySelectorAll(queryChildren).length-1) {
But you've already collected that above:
code:
var carItems = document.querySelectorAll(queryChildren);
So I'd just use carItems.length-1 instead of calling the query every time.

Also: Your function takes a slidesDefault, which you use when the window.innerWidth <= 1024, but then you also have
code:
	if (numSlides == undefined) {
		numSlides = 3;
	}
I don't think you need this level of defensive programming. It's the responsibility of the caller of the function to give you actual values for slidesDefault and slidesDesktop

Adbot
ADBOT LOVES YOU

LifeLynx
Feb 27, 2001

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

code:
function endlessCarousel( query, queryChildren, speed, slidesDefault, slidesWide ) {

	var theCarousel = document.querySelector(query);	
	var carWidth = document.querySelector(query).offsetWidth;
	var carItems = document.querySelectorAll(queryChildren);
	var numSlides = slidesDefault;
	var carIndex = 1;
	var currentTarget = 0;
	var animSpeed = 2000;

	if (window.innerWidth > 1024) {
		numSlides = slidesWide;
	}

	function resetCarousel() {
		animSpeed = speed;
		carItems.forEach(function(carItem) {
			carItem.width = carWidth/numSlides;
			carIndex = 0;
			currentTarget = 0;
			carItem.style.order = carIndex;
			carItem.style.marginLeft = 0;
			carItem.style.opacity = 0.5;
		});
	}

	function hideCurrentItem() {
		theCarousel.children[currentTarget].style.opacity = 0;
		theCarousel.children[currentTarget].style.marginLeft = '-' + carWidth/numSlides + 'px';
	}

	function showNextItem() {
		carIndex++;
		theCarousel.children[currentTarget].style.order = carIndex;
		theCarousel.children[currentTarget].style.opacity = 0.5;
		theCarousel.children[currentTarget].style.marginLeft = 0;
		currentTarget++;
		if (currentTarget > carItems.length-1) {
				currentTarget = 0;
			}
	}

	function scrollCarousel() {		
		hideCurrentItem();
		setTimeout(showNextItem, animSpeed/2);
	}

	var setTimer = setInterval(scrollCarousel, animSpeed);

	carObserver = new IntersectionObserver(entries => {
		entries.forEach(entry => {
			if (entry.isIntersecting) {
				resetCarousel();
				clearInterval(setTimer);
				setTimer = setInterval(scrollCarousel, animSpeed);
			}
			else {
				clearInterval(setTimer);
				resetCarousel();
			}
		});
	});

	carObserver.observe(theCarousel);
}

document.addEventListener("DOMContentLoaded", endlessCarousel('.carousel', '.carousel .carousel--item', 2000, 3, 5));
The scrollCarousel() in that old loop was because the first item wasn't moving properly until the full cycle was done, due to the order I had things written. Now every two seconds, scrollCarousel fires, starting hideCurrentItem to "scroll" the current item by fading it out and giving it a left margin. It also fires showNextItem, which waits one second (after which the current item is already opacity 0 and totally off the side of the parent element) and moves the current item to the end of the line via flex order. Then it unhides it so it's ready to scroll into view. You're right, I don't need the defensive programming, no one besides myself is going to use this anyway.

Osmosisch posted:

I think it's perfectly functional, but I'd definitely prefer coding and writing a different style where for example the images are not already hardcoded in the html but added from data in code, and where there's fewer globals. I definitely would rather be taking the head off the list of images and adding it to the tail rather than doing index math for example.

I think the images are always going to be hardcoded into the HTML, because this is meant to be used on my Wordpress sites where I need a simple carousel to display, like, logos of brands the client works with or whatever. I always find it's easier for me to visualize what's going on if I break things into sensible globals and functions and then work back to see exactly what needs to be in its own global or function. What do you mean about taking the head off the list of images and adding it to the tail?

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