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
minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender

Kraus posted:

I'm still messing with code golf* and was wondering if anyone had any advice for shrinking this implementation(JavaScript) of FizzBuzz down. Apparently it can be done in 36 fewer characters?

I reduced it by 19 chars by moving the loop increment into conditional check, and using an array lookup to select from one of the 4 combos.
code:
for(i=0;i++<101;)document.write([i,"Buzz","Fizz","FizzBuzz"][(i%3==0)*2+(i%5==0)]+"<br>")
There's probably lots of other tricks I missed, but I'm not a JavaScript expert.

quote:

*I'm not doing it for points on any site, just to become a better programmer.
Depends what you mean by "better". You'll end up discovering lots of crazy esoteric syntax hacks and language quirks, and it's often helpful to be aware of those. But as others have pointed out, it's easier on you and your co-workers if you write clearly, rather than trying to be clever.

Adbot
ADBOT LOVES YOU

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!
Generally codegolf sites give you something shorter than document.write to work with, so there's probably like 10 characters saved there in the number you're citing unless it was explicitly specified this many characters with document.write.

Kraus
Jan 17, 2008

roomforthetuna posted:

Generally codegolf sites give you something shorter than document.write to work with, so there's probably like 10 characters saved there in the number you're citing unless it was explicitly specified this many characters with document.write.

Yeah, the site in question would let you use "print()", and it does the same as "document.write(+"<br>"); Saves 16 characters, but I'm taking that into account.

And to everyone dunking on code golf: I would never write actual software this way. I know the difference between writing proper code and having fun. But, as it was pointed out, code golf will absolutely help you learn some esoteric stuff about your language(s), which is largely what I'm after, because yes, more knowledge does make you better.

EDIT:

minato posted:

I reduced it by 19 chars by moving the loop increment into conditional check, and using an array lookup to select from one of the 4 combos.
code:
for(i=0;i++<101;)document.write([i,"Buzz","Fizz","FizzBuzz"][(i%3==0)*2+(i%5==0)]+"<br>")
There's probably lots of other tricks I missed, but I'm not a JavaScript expert.

Depends what you mean by "better". You'll end up discovering lots of crazy esoteric syntax hacks and language quirks, and it's often helpful to be aware of those. But as others have pointed out, it's easier on you and your co-workers if you write clearly, rather than trying to be clever.

You can knock off another four characters by using ! instead of ==0 for the division!

code:

for(i=0;i++<100;)document.write([i,"Buzz","Fizz","FizzBuzz"][!(i%3)*2+!(i%5)]+"<br>")

Kraus fucked around with this message at 06:14 on Apr 4, 2019

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender
I just noticed you can knock off another 3:
code:
- [i,"Buzz","Fizz","FizzBuzz"]
+ [i,b="Buzz",f="Fizz",f+b]

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



Kraus posted:

Yeah, the site in question would let you use "print()", and it does the same as "document.write(+"<br>"); Saves 16 characters, but I'm taking that into account.

Ah rats I was going to point out that document.writeln exists

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
i would be happy if people never saw the !~arr.indexOf(n) trick again

The Fool
Oct 16, 2003


I have been spending a couple weeks on a new project and have come to a conclusion:


Typescript is really good.


That is all.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Suspicious Dish posted:

i would be happy if people never saw the !~arr.indexOf(n) trick again

amen

lunar detritus
May 6, 2009


The Fool posted:

I have been spending a couple weeks on a new project and have come to a conclusion:


Typescript is really good.


That is all.

It is! I wish I could convince more people at work to switch to Typescript outside of Angular. Too many Ruby programmers who don't see why types are useful :negative:

Joda
Apr 24, 2010

When I'm off, I just like to really let go and have fun, y'know?

Fun Shoe

Suspicious Dish posted:

i would be happy if people never saw the !~arr.indexOf(n) trick again

:negative: I'm gonna try to sneak this through a code review at some point, for shits and giggles.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I wish typescript would allow me to compile to ES5 IIFE. Instead of forcing me to use typescript -> rollup -> buble.

The Fool
Oct 16, 2003


There is an npm package that I want to use on my project. However, I want to have it downloaded and added to my own repo so I don't have to worry about it going away or other changes being made.

What's the best way to do this? I was going to try doing it by hand, but npm dependency chains are ridiculous.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Nolgthorn posted:

I wish typescript would allow me to compile to ES5 IIFE. Instead of forcing me to use typescript -> rollup -> buble.

The SystemJS exporter is close. I used that for a while.

Tanners
Dec 13, 2011

woof

The Fool posted:

There is an npm package that I want to use on my project. However, I want to have it downloaded and added to my own repo so I don't have to worry about it going away or other changes being made.

What's the best way to do this? I was going to try doing it by hand, but npm dependency chains are ridiculous.

Couldn't you just lock the version in your package.json? Afaik you can't remove a package from the npm registry after its been up for 24 hours.

The Fool
Oct 16, 2003


FWIW I solved this by finding the github repo of the package in question, forked it, then did npm install --save thefool/forkedrepo

underage at the vape shop
May 11, 2011

by Cyrano4747
Hi, I'm learning react. Whats the correct way to have a form appear when you press a button? My code is really bad right now, but here it is in codesandbox

https://codesandbox.io/s/oq4682rym9

Basically the idea is that you have a menu bar up the top and everything you work with underneath. Its using an api supplied by my uni that has a tonne of crime stats for my state. Eventually they are going to be mapped and graphed. Currently I'm trying to make a register form appear when you hit the register button. It appears but when you submit it, chrome says the submission is cancelled because its not connected. Whats the correct way of doing this?

E: the uni is pretty unhelpful right now, this stuff isnt in the lecture notes, they are still writing this assignment. This is the first semester they've done react

underage at the vape shop fucked around with this message at 03:54 on Apr 5, 2019

necrotic
Aug 2, 2005
I owe my brother big time for this!
You need another piece of boolean state, say showMenu, and then render the form conditionally: {showMenu && <regButton/>}. The onClick handler for the button should be () => setShowMenu(!showMenu).

You should not be putting elements into state like you are with the offences button. The state should be data, and then the data is used when rendering elements.

underage at the vape shop
May 11, 2011

by Cyrano4747

necrotic posted:

You need another piece of boolean state, say showMenu, and then render the form conditionally: {showMenu && <regButton/>}. The onClick handler for the button should be () => setShowMenu(!showMenu).

You should not be putting elements into state like you are with the offences button. The state should be data, and then the data is used when rendering elements.

How should I handle when I want to render different thngs? A seperate hook to tell it what to render? Ie render the register form, render the login form (probably reuse the form and set the button/submit handling dependent on state?), and in future the graphing stuff and mapping stuff?

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

underage at the vape shop posted:

How should I handle when I want to render different thngs? A seperate hook to tell it what to render? Ie render the register form, render the login form (probably reuse the form and set the button/submit handling dependent on state?), and in future the graphing stuff and mapping stuff?

That sounds dangerously like routing to me.

RobertKerans
Aug 25, 2006

There is a heppy lend
Fur, fur aw-a-a-ay.

underage at the vape shop posted:

How should I handle when I want to render different thngs? A seperate hook to tell it what to render? Ie render the register form, render the login form (probably reuse the form and set the button/submit handling dependent on state?), and in future the graphing stuff and mapping stuff?

Again, just think about it at the data level, and as quite basic operations on that. You could have flags for each one (though that will get unwieldy), or you can delegate out to another function that decides on what to render based on what the button clicks do, for example:

code:
renderMyStuff = (whatIWantToRender) => {
  switch (whatIWantToRender) {
    case "REGISTER":
      return <RegisterForm />;
    case "LOGIN":
      return <LoginForm />;
    case "GRAPH_THING":
      return <GraphThing />;
    case "MAP_THING":
      return <MapThing />;
    default:
      return null;
}
where "whatIWantToRender" is stored in the state and gets updated by the relevant button click. This will all get spaghetti-like pretty quickly because it's very unlikely you just want to render, you normally want to do things like enable/disable things and conditionally do other UI stuff based on what the user is doing in the app

Lumpy posted:

That sounds dangerously like routing to me.

RobertKerans fucked around with this message at 13:05 on Apr 5, 2019

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
Under what circumstances will importing a JavaScript file as a module trip a CORS error?

I converted my class's codebase to use module import statements to bring in all the JavaScript. Suddenly, many of my students are having problems, including with the following error:

quote:

Access to script at 'file:///Users/Name/Documents/GitHub/a1-githubName/main-scene.js' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Failed to load resource: net::ERR_FAILED main-scene.js:1

We're opening this by visiting localhost, while the .html and .js files are hosted locally using python. One of my TAs added a little bit of python code to patch in corrected MIME types for some people who were having trouble with that on modules, but that hasn't been enough to fix the above error some students are now getting. Help!

mystes
May 31, 2006

Dumb Lowtax posted:

Under what circumstances will importing a JavaScript file as a module trip a CORS error?

I converted my class's codebase to use module import statements to bring in all the JavaScript. Suddenly, many of my students are having problems, including with the following error:


We're opening this by visiting localhost, while the .html and .js files are hosted locally using python. One of my TAs added a little bit of python code to patch in corrected MIME types for some people who were having trouble with that on modules, but that hasn't been enough to fix the above error some students are now getting. Help!
If you're hosting it from a python script why is the error saying it's a file url?

You can't load JavaScript from file urls in 2019 (without a dangerous chrome command line option).

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
Good eye, so the two students who have this problem are simply the two who didn't follow directions. They double-clicked index.html after hosting, instead of navigating to localhost:8000. Thank you!

The Fool
Oct 16, 2003


Dumb Lowtax posted:

Good eye, so the two students who have this problem are simply the two who didn't follow directions. They double-clicked index.html after hosting, instead of navigating to localhost:8000. Thank you!

If your students were using vs code they could just hit launch from their IDE and it could launch the python process and chrome automatically.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop

The Fool posted:

If your students were using vs code they could just hit launch from their IDE and it could launch the python process and chrome automatically.

Yeah at this point it's obvious that I should have gone with that, I even tell them that it's probably better for all purposes. Next time. For now I ran out of preparation time before school started and didn't get to try it myself.

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

Dumb Lowtax posted:

Yeah at this point it's obvious that I should have gone with that, I even tell them that it's probably better for all purposes. Next time. For now I ran out of preparation time before school started and didn't get to try it myself.

This is great to read, I was worried you would keep going down this rabbit hole. Kudos, hope the class goes well.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
Someone code golfed a chess ai. I've tried to write a chess ai in javascript and it isn't easy so this is quite an accomplishment while also being an example of why you should never code golf.

http://www.nanochess.org/chess4.html

code:
var B,i,y,u,b,I=[],G=120,x=10,z=15,M=1e4,l=[5,3,4,6,2,4,3,5,1,1,1,1,1,1,1,1,9,9
,9,9,9,9,9,9,13,11,12,14,10,12,11,13,0,99,0,306,297,495,846,-1,0,1,2,2,1,0,-1,-
1,1,-10,10,-11,-9,9,11,10,20,-9,-11,-10,-20,-21,-19,-12,-8,8,12,19,21];function
X(w,c,h,e,S,s){var t,o,L,E,d,O=e,N=-M*M,K=78-h<<x,p,g,n,m,A,q,r,C,J,a=y?-x:x;
y^=8;G++;d=w||s&&s>=h&&X(0,0,0,21,0,0)>M;do{if(o=I[p=O]){q=o&z^y;if(q<7){A=q--&
2?8:4;C=o-9&z?[53,47,61,51,47,47][q]:57;do{r=I[p+=l[C]];if(!w|p==w){g=q|p+a-S?0
:S;if(!r&(!!q|A<3||!!g)||(r+1&z^y)>9&&q|A>2){if(m=!(r-2&7))return y^=8,I[G--]=
O,K;J=n=o&z;E=I[p-a]&z;t=q|E-7?n:(n+=2,6^y);while(n<=t){L=r?l[r&7|32]-h-q:0;if(
s)L+=(1-q?l[(p-p%x)/x+37]-l[(O-O%x)/x+37]+l[p%x+38]*(q?1:2)-l[O%x+38]+(o&16)/2:
!!m*9)+(!q?!(I[p-1]^n)+!(I[p+1]^n)+l[n&7|32]-99+!!g*99+(A<2):0)+!(E^y^9);if(s>h
||1<s&s==h&&L>z|d){I[p]=n,I[O]=m?(I[g]=I[m],I[m]=0):g?I[g]=0:0;L-=X(s>h|d?0:p,L
-N,h+1,I[G+1],J=q|A>1?0:p,s);if(!(h||s-1|B-O|i-n|p-b|L<-M))return W(),G--,u=J;
J=q-1|A<7||m||!s|d|r|o<z||X(0,0,0,21,0,0)>M;I[O]=o;I[p]=r;m?(I[m]=I[g],I[g]=0):
g?I[g]=9^y:0;}if(L>N||s>1&&L==N&&!h&&Math.random()<.5){I[G]=O;if(s>1){if(h&&c-L
<0)return y^=8,G--,L;if(!h)i=n,B=O,b=p;}N=L;}n+=J||(g=p,m=p<O?g-3:g+2,I[m]<z|I[
m+O-p]||I[p+=p-O])?1:0;}}}}while(!r&q>2||(p=O,q|A>2|o>z&!r&&++C*--A));}}}while(
++O>98?O=20:e-O);return y^=8,G--,N+M*M&&N>-K+1924|d?N:0;}B=i=y=u=0;while(B++<
120)I[B-1]=B%x?B/x%x<2|B%x<2?7:B/x&4?0:l[i++]|16:7;for(a=
"<table cellspacing=0 align=center>",i=18;i<100;a+=++i%10-9?
"<th width=40 height=40 onclick=Y("+i+") style='border:2px solid #aae' id=o"+i+
" bgcolor=#"+(i*.9&1?"9090d0>":"c0c0ff>"):(i++,"<tr>"));
a+="<th colspan=8><select id=t><option>Q<option>R<option>B";
document.write(a+"<option>N</select></table>");
function W(){B=b;for(p=21;p<99;++p)if(q=document.getElementById("o"+p)){q.
innerHTML="<img width=40 src="+(I[p]&z)+".gif>";q.
style.borderColor=p==B?"#ff0":"#aae";}}W();
function Y(s){i=(I[s]^y)&z;if(i>8){b=s;W();}else if(B&&i<9){b=s;i=I[B]&z;if((i&
7)==1&(b<29|b>90))i=14-document.getElementById("t").selectedIndex^y;X(0,0,0,21,
u,1);if(y)setTimeout("X(0,0,0,21,u,2/*ply*/),X(0,0,0,21,u,1)",250);}}
Oh god.

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Dumb Lowtax posted:

Yeah at this point it's obvious that I should have gone with that, I even tell them that it's probably better for all purposes. Next time. For now I ran out of preparation time before school started and didn't get to try it myself.


Osmosisch posted:

This is great to read, I was worried you would keep going down this rabbit hole. Kudos, hope the class goes well.

I agree with this person.

So often people just stick to their guns or at least don't say they've changed their minds, and it restores my faith in humanity to hear someone at least go "well, you know, you guys have got a point".

When someone does this, it always makes me nervous that I'm not saying it out loud when I've changed my mind or learned something enough.

The Fool
Oct 16, 2003


I spent the weekend setting up webpack for a react/typescript app by hand, with webpack-dev-server, html-webpack-plugin, and source maps/chrome debugger.

It's one of those things that I'd recommend everyone do at least once, and then just continue using CRA then ejecting when ready.

Thermopyle posted:

I agree with this person.

So often people just stick to their guns or at least don't say they've changed their minds, and it restores my faith in humanity to hear someone at least go "well, you know, you guys have got a point".

When someone does this, it always makes me nervous that I'm not saying it out loud when I've changed my mind or learned something enough.

:same:

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

The Fool posted:

I spent the weekend setting up webpack for a react/typescript app by hand, with webpack-dev-server, html-webpack-plugin, and source maps/chrome debugger.

It's one of those things that I'd recommend everyone do at least once, and then just continue using CRA then ejecting when ready.


You know, I spent a weekend doing that I came out with a different lesson: once I knew how it all worked, I just stopped using CRA. In large part because hardly anything changes between projects so I can just copy/paste my base config.

Anony Mouse
Jan 30, 2005

A name means nothing on the battlefield. After a week, no one has a name.
Lipstick Apathy
Parcel is the poo poo and you should believe the hype and use it. I'm pretty comfortable with Webpack and I pretty much only use it at work because I'm forced to. That said CRA -> Webpack -> Parcel is a nice progression because you learn how poo poo actually works (well, as much as anyone can when it comes to bundlers anyway) and can make an informed decision about what tools to use instead of throwing the same boilerplate at every project.

Anony Mouse fucked around with this message at 03:55 on Apr 9, 2019

Roadie
Jun 30, 2013
I will second the Parcel recommendation, because it just automatically does the right thing for most files without having to screw around with loaders, plus hacky but consistent syntax for getting the raw string contents of any file embedded without passing through loader/plugin stuff.

The one problem is their incredibly stupid thing where it auto-installs dependencies by default.

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!
I don't use Parcel, but I back the recommendation anyway, because unless you want to do some wacky combination like typescript with dynamic module loading it's way less of a headache than the alternatives.

SnatchRabbit
Feb 23, 2006

by sebmojo
I have an html table with a set of key:value pairs for tags. I want to reference certain values in another function. The problem is the order and amount of tags in the table is going to vary so I can't do a document.getElementById("myvalue").value = this.cells[3].innerHTML; as I was before since I don't know when that value is going to show up in the row. I'm thinking I put in an if statement something inside of the loop. Something to the effect of:

code:
for(var i = 1; i < table.rows.length; i++)
   if this.cells[i].innerHTML = 'mykey'
       document.getElementById("myvalue").value = this.cells[i+1].innerHTML;
Would this work?

The Fool
Oct 16, 2003


Why are you getting data out of your HTML?

Can you store your data in an object? Then both generate your table from that and reference it in your other function easier.

SnatchRabbit
Feb 23, 2006

by sebmojo

The Fool posted:

Why are you getting data out of your HTML?

Can you store your data in an object? Then both generate your table from that and reference it in your other function easier.

I suppose I could. The idea is that the table has a list of objects data and the user and perform actions based on the selection they make on the table.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
I know they've got special attributes you can add to an HTML tag that begin with "data-", which automatically add that string as a data member to the DOM element (HTML tag) so that you can see it from JavaScript -- think of it as a way HTML structures can communicate information to JavaScript. However, communication to go that direction at all might be kind of a code smell, or an indicator that your approach is backwards. For example, I had one of these "data-" attributes in my infamous "code navigator" upthread, to help it remember which source code it had populated a text box with. One day I refactored my code to be more encapsulated and suddenly this awkward thing I thought I had no other choice to use was no longer needed.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
If you've got some digital clocks on your page. You've got javascript that loops though all the ".clock" elements and starts updating them every second that passes, but you want them in different timezones you might set "data-timezone" attributes so that in your javascript you just have to look at the element's "data.timezone".

It's super useful if your entire page isn't js.

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!

Nolgthorn posted:

If you've got some digital clocks on your page. You've got javascript that loops though all the ".clock" elements and starts updating them every second that passes, but you want them in different timezones you might set "data-timezone" attributes so that in your javascript you just have to look at the element's "data.timezone".

It's super useful if your entire page isn't js.
Yeah, it's good where you want to communicate something from your raw html content to your javascript. If you find yourself populating data attributes from your javascript you're probably doing something daft.

Adbot
ADBOT LOVES YOU

Roadie
Jun 30, 2013

SnatchRabbit posted:

I suppose I could. The idea is that the table has a list of objects data and the user and perform actions based on the selection they make on the table.

You should be (re)generating the table from the authoritative data set, not trying to reverse-engineer stuff out of the page HTML..

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