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
necrotic
Aug 2, 2005
I owe my brother big time for this!
Try wrapping the last bit in parentheses. Ternary and binary or have different presedence rules.

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Kraus posted:


For some reason, this simply doesn't work. If you replace the "success" part with something like alert("success"), this works just fine. I, for the life of me, have no idea why Javascript doesn't like the version with the getElementById. Anyone know why?

Because it's a syntax error. Put the document.getElementById("success").style.display = "block" inside parenthesis and it should work.

e:;b :argh:

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.

quote:

For some reason, this simply doesn't work. If you replace the "success" part with something like alert("success"), this works just fine. I, for the life of me, have no idea why Javascript doesn't like the version with the getElementById. Anyone know why?

Debugger says: Invalid left hand sign in assignment.

I think it's doing:
code:
(document.getElementsByClassName("red").length || document.getElementById("success").style.display) = "block"
If you don't provide the parenthesis

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
I'm not someone who regularly writes inexplicit javascript but I imagine `&&` has as much to do with it. Javascript is trying to form a boolean and is likely optimising your assignment out of the operation.

Kraus
Jan 17, 2008

necrotic posted:

Try wrapping the last bit in parentheses. Ternary and binary or have different presedence rules.

Ah, yeah, that totally did it! Thanks!

What's funny, for golf purposes, these solutions are only better than the other depending on if you're counting spaces or not.

Ternary: 142 counting spaces, 132 not.

Or: 141 counting spaces, 133, not.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Nolgthorn posted:

I'm not someone who regularly writes inexplicit javascript but I imagine `&&` has as much to do with it. Javascript is trying to form a boolean and is likely optimising your assignment out of the operation.

given "a ? b : c"

code:
(para.className = "yellow") && document.getElementsByClassName("red").length ? 0 : document.getElementById("success").style.display = "block"; 
 
a is (para.className = "yellow") && document.getElementsByClassName("red").length
b is 0
c is document.getElementById("success").style.display = "block";

given "a = b"
code:
(para.className = "yellow") && document.getElementsByClassName("red").length || document.getElementById("success").style.display = "block"; 
a is (para.className = "yellow") && document.getElementsByClassName("red").length || document.getElementById("success").style.display
b is 'block'

you cannot assign a value to a statement.

AND and OR have highest precedent, conditional statement has a higher precedence than assignment operator

Kraus
Jan 17, 2008

Strong Sauce posted:

AND and OR have highest precedent, conditional statement has a higher precedence than assignment operator

This makes total sense for why the parentheses are required! Thanks for the theoretical reason!

biznatchio
Mar 31, 2001


Buglord

Kraus posted:

Ah, yeah, that totally did it! Thanks!

What's funny, for golf purposes, these solutions are only better than the other depending on if you're counting spaces or not.

Ternary: 142 counting spaces, 132 not.

Or: 141 counting spaces, 133, not.

For real golf improvement you need to move some of the longer stuff out into variables and use a efficiently-named function to find elements, e.g.:

code:
d=document,q=d.querySelector.bind(d),para.className="yellow";q(".red")||(q("#success").style.display="block")

Kraus
Jan 17, 2008

biznatchio posted:

For real golf improvement you need to move some of the longer stuff out into variables and use a efficiently-named function to find elements, e.g.:

code:
d=document,q=d.querySelector.bind(d),para.className="yellow";q(".red")||(q("#success").style.display="block")

Wow. I need to up my game, severely.

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender
You don't even have to set style.display to anything, save 14 chars with
code:
(q("#success").style=0)

Kraus
Jan 17, 2008

minato posted:

You don't even have to set style.display to anything, save 14 chars with
code:
(q("#success").style=0)

So, you're basically deleting all its style information and it defaults to displaying.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
You guys please consider using uglify-js and writing normal code for us garbage humans.

Kraus
Jan 17, 2008
Oh god, this thread has gotten me more into code golfing in JS, and I found a site (https://code-golf.io/) that offered some challenges. I decided to tackle the Fibonacci challenge, where you have to get the Fibonacci sequence to display from 0 to 832,040, each on their own line.

I managed to come up with this 71-character solution:

code:
a=[-1,1];for(i=2;i<33;i++){document.write((a[i]=a[i-2]+a[i-1])+"<br>")}
But, the leaderboards on that site claim that it can be done in as little as 33 characters. Does anyone have any idea how?

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender
There's a way of generating fib(n) without generating fib(n-1), i.e. in O(1) time. It's a very good tool for looking :smug: in interviews. Here's some snackoverflow code I copied, but it could easily be code-golfed to something much smaller.

code:
function fib (n) {
  var A=(1+Math.sqrt(5))/2,
      B=(1-Math.sqrt(5))/2,
      fib = (Math.pow(A,n) - Math.pow(B,n)) / Math.sqrt(5);
      return Math.ceil(fib);
}

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!

Kraus posted:

But, the leaderboards on that site claim that it can be done in as little as 33 characters. Does anyone have any idea how?
Recursion is pretty much always shorter than iteration.

Doom Mathematic
Sep 2, 2008

Kraus posted:

Oh god, this thread has gotten me more into code golfing in JS, and I found a site (https://code-golf.io/) that offered some challenges. I decided to tackle the Fibonacci challenge, where you have to get the Fibonacci sequence to display from 0 to 832,040, each on their own line.

I managed to come up with this 71-character solution:

code:
a=[-1,1];for(i=2;i<33;i++){document.write((a[i]=a[i-2]+a[i-1])+"<br>")}
But, the leaderboards on that site claim that it can be done in as little as 33 characters. Does anyone have any idea how?

You can save a lot of characters by using print(...) to output with a newline instead of document.write(... + '<br>'). This isn't standard JavaScript but it's in the instructions so it works for me.

Declaring and indexing that array is costly since we only need the two most recent entries (and I think a third variable to use as a temporary variable while we step forward...)

Also, cunningly the last entry requested is the last entry before Fibonacci numbers pass a million, which has a very small representation in JavaScript. So, here's what I have currently:

JavaScript code:
a=0;b=1;while(b<1e6){print(b);c=a+b;a=b;b=c}
(44 chars)

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!

Doom Mathematic posted:

JavaScript code:
a=0;b=1;while(b<1e6){print(b);c=a+b;a=b;b=c}
(44 chars)
(NB. that gets the beginning slightly wrong)
And then save some chars with the recursion effect:
JavaScript code:
f=(a,b)=>(print(a),b<1e6&&f(b,a+b));f(0,1)
(42 chars)

Kraus
Jan 17, 2008
Uh, all print did was repeatedly call a dialogue box for physically printing things.

Doom Mathematic
Sep 2, 2008

Kraus posted:

Uh, all print did was repeatedly call a dialogue box for physically printing things.

I think you're running your code in your browser console. Try running on https://code-golf.io/fizz-buzz#javascript itself like you mentioned.

Kraus
Jan 17, 2008

Doom Mathematic posted:

I think you're running your code in your browser console. Try running on https://code-golf.io/fizz-buzz#javascript itself like you mentioned.

Okay. Hmm. That seems a little janky if it doesn't always work, and is just environment-specific. Oh well.

Edit: What I'm saying is that if you wanted to run this code outside of that environment, you'd end up having to write 16 characters more, since "print()" does something else outside of that environment. That means the record is a stealth 49, unless y'all know another way to get stuff to appear on screen, formatted that way.

Kraus fucked around with this message at 19:39 on Jan 30, 2019

Doom Mathematic
Sep 2, 2008

Kraus posted:

Okay. Hmm. That seems a little janky if it doesn't always work, and is just environment-specific. Oh well.

Edit: What I'm saying is that if you wanted to run this code outside of that environment, you'd end up having to write 16 characters more, since "print()" does something else outside of that environment. That means the record is a stealth 49, unless y'all know another way to get stuff to appear on screen, formatted that way.

Yeah, JavaScript environments differ from one another. Not all of them are web browsers. The challenge as stated doesn't require the code to run outside of the environment it provides, which, by the way, isn't a web browser, document.write doesn't work there.

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
What I prefer is that the code doesn't work as long as I can reserve 16 characters. In fact typing this sentence is making my hands sweat.

huhu
Feb 24, 2006
Thanks for sucking up my entire afternoon and evening with code golf.

Kraus
Jan 17, 2008
A friend of mine managed to bring it down to 36 characters:

code:
for(a=1,b=0;b<9e5;b=a+(a=b))print(b)
Where could there be three characters to save?

MrMoo
Sep 14, 2000

Kraus posted:

A friend of mine managed to bring it down to 36 characters:

code:
for(a=1,b=0;b<9e5;b=a+(a=b))print(b)
Where could there be three characters to save?

You should be able to avoid that “b=0” setup.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





MrMoo posted:

You should be able to avoid that “b=0” setup.

you cannot compare a variable to something before it has been defined. you will get a reference error when the engine gets to b<9e5.

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe
that's the challenge, yes.

biznatchio
Mar 31, 2001


Buglord

minato posted:

You don't even have to set style.display to anything, save 14 chars with
code:
(q("#success").style=0)

Huh, I didn't know that worked. Turns out you can do

code:
(q("#success").style++)
too. And since this eliminates the assignment operator, it also eliminates the need for the enclosing parenthesis resulting in another net loss of two more characters.

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender
You can also save a single char with:
code:
q("[id*=s]");
i.e. it selects the first element with id matching the regex "s". (Use "id^=s" for the first element starting with "s" if that doesn't work in your page)

Anony Mouse
Jan 30, 2005

A name means nothing on the battlefield. After a week, no one has a name.
Lipstick Apathy

minato posted:

You can also save a single char with:
code:
q("[id*=s]");
i.e. it selects the first element with id matching the regex "s". (Use "id^=s" for the first element starting with "s" if that doesn't work in your page)

In that case why not just

code:
q('[id]');

minato
Jun 7, 2004

cutty cain't hang, say 7-up.
Taco Defender
Oh nice. Didn't realize that was the only element with an id in the page. So that saves 4 chars.

Anony Mouse
Jan 30, 2005

A name means nothing on the battlefield. After a week, no one has a name.
Lipstick Apathy
My take:
code:
para.className='yellow';document.querySelector('[id],.red').style.display=null;
79 chars

Anony Mouse fucked around with this message at 07:49 on Feb 2, 2019

smackfu
Jun 7, 2004

Roadie posted:

Don't forget the true galaxy brain approach:
JavaScript code:
[...new Set(a.map(JSON.stringify))].map(JSON.parse)

I actually saw some similar code yesterday in a package we are using.
code:
 const improvedSpec = JSON.parse(JSON.stringify(inputSpec));
https://github.com/Surnet/swagger-jsdoc/blob/master/lib/helpers/getSpecificationObject.js

What the heck?

Doom Mathematic
Sep 2, 2008

smackfu posted:

I actually saw some similar code yesterday in a package we are using.
code:
 const improvedSpec = JSON.parse(JSON.stringify(inputSpec));
https://github.com/Surnet/swagger-jsdoc/blob/master/lib/helpers/getSpecificationObject.js

What the heck?

That's an extremely common way to clone a JavaScript object. It can be very lossy but it's also surprisingly fast. It also avoids pulling in a third-party deep cloning library whose behaviour with respect to e.g. circular objects is less well-understood than JSON.parse and JSON.stringify, which are universally known quantities.

Of course, in most cases it should not be necessary to completely clone an object in this way... for example, in this case const improvedSpec = { ...inputSpec } would do the same job much faster still...

smackfu
Jun 7, 2004

Interesting, I figured they were using stringify to validate the user-provided JSON but couldn’t figure out why they were then parsing and using the result.

Kraus
Jan 17, 2008

Anony Mouse posted:

My take:
code:
para.className='yellow';document.querySelector('[id],.red').style.display=null;
79 chars

Whoa.

So combining that with biznatchio's realization you can just do .style++, and cutting all the class, ID, and variable names down to one character each, that gives us a 55 character solution:

code:
 p.className='y';document.querySelector('#s,.r').style++
A version of the exercise, with all the ID, class, and variable names cut down to one character each is here: https://ufile.io/8i4p4

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:

Interesting, I figured they were using stringify to validate the user-provided JSON but couldn’t figure out why they were then parsing and using the result.

i've definitely made a utility method "copy" and stuck that JSON stringify/JSON parse in there. javascript is always pass by value, but if a variable return to an object, the "value" is a reference to the object - this means if you do something like slicing an array, and modify a property of the element in the sliced array, the element in the original array will also be modified, and you can stop that from happening by doing this.

Strong Sauce
Jul 2, 2003

You know I am not really your father.





Bruegels Fuckbooks posted:

i've definitely made a utility method "copy" and stuck that JSON stringify/JSON parse in there. javascript is always pass by value, but if a variable return to an object, the "value" is a reference to the object - this means if you do something like slicing an array, and modify a property of the element in the sliced array, the element in the original array will also be modified, and you can stop that from happening by doing this.

no slice makes a copy of the array
code:
a = [1,2,3,4]
b = a.slice(1,3)
// b = [2,3]
b[0] = 100
//a: [1,2,3,4]
//b: [100, 3]
what you're probably thinking about is something like

code:
a = [1,2,3,4]
b = a
a[0] = 100
//a: [100,2,3,4]
//b: [100,2,3,4]

necrotic
Aug 2, 2005
I owe my brother big time for this!
That is true for scalar objects, but not for everything else. misread the post at first, but the rest is relevant

code:
var a = [{foo: 'bar'}];
var b = a.slice(0);

b[0].foo = 'oops';
console.log(a[0].foo); // oops
Reassigning an element of the copied array does not change the original array. It is a new array, but the elements are references.

necrotic fucked around with this message at 22:37 on Feb 2, 2019

Adbot
ADBOT LOVES YOU

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
I feel like if you've got a good background on pointers and references from a C++ background or a quality CS intro class you just don't ever have that misunderstanding

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