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
5TonsOfFlax
Aug 31, 2001

Rosalind posted:

I am very, very new to using Javascript and sometimes have to write little snippets for my workplace. I am trying to have a function that reads something from the url and then uses it to pass along some info in a url when the participant clicks on a link. The code I wrote works on most modern web browsers but I just had someone testing the website out come back to me and say that on their iPhone 5 with Safari they got an error message. This is the code:

code:
function getCity() {
    var cityurl = document.referrer;
    var citystart = cityurl.search("city=");
    var city = "0";
    if (citystart > 0) {
        var city = cityurl.substring(citystart + 5);
    }
    var link = "(a website url)?City=" + city;
    window.open(link);
}
Am I doing anything obviously wrong that would affect an older browser?

In addition to the double declaration of city, I would guess that mobile safari might not support the "search" method you're using. Since search takes a regex, but you're not using any regex features, you can replace it with indexOf. Also, you probably want to compare citystart to -1 instead of 0, or use >=

Adbot
ADBOT LOVES YOU

Rosalind
Apr 30, 2013

When we hit our lowest point, we are open to the greatest change.

Thanks for all the feedback. I made the suggested changes (removed the duplicate variable declaration, changed search to indexOf, changed the comparison to -1 instead of 0). Unfortunately she's still having the issue. Referrer definitely works on other iPhones including older models so I'm not sure that that's it.

reversefungi
Nov 27, 2003

Master of the high hat!

Rosalind posted:

Thanks for all the feedback. I made the suggested changes (removed the duplicate variable declaration, changed search to indexOf, changed the comparison to -1 instead of 0). Unfortunately she's still having the issue. Referrer definitely works on other iPhones including older models so I'm not sure that that's it.

Have you checked it on the same version of iOS/Safari on another phone? Wild guess but maybe she has some settings block or something that affects document.referrer?

If I were in your shoes, I'd probably write out the values of each variable onto a dom element, then ask her to take a screenshot of what it prints out.

Something like:
code:
function getCity() {
    var cityurl = document.referrer;
    var elCityUrl = document.getElementById("cityurl);
    elCityUrl.innerHTML = "var cityurl = " + cityurl;

   //etc.
}
I've never debugged on mobile Safari before, but google tells me there's something called Web Inspector you could use for this whole thing if you're using Apple stuff. Might be worth looking into?

Nolgthorn
Jan 30, 2001

The pendulum of the mind alternates between sense and nonsense
https://www.htmlgoodies.com/beyond/webmaster/toolbox/article.php/3889011/Using-Safari-for-iPhone-iPad-and-iPod-Touch-Website-Testing.htm

Ooh.

Safari -> Preferences -> Advanced -> Show developer menu -> Right click -> User Agent -> Select any safari you want.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Rosalind posted:

Thanks for all the feedback. I made the suggested changes (removed the duplicate variable declaration, changed search to indexOf, changed the comparison to -1 instead of 0). Unfortunately she's still having the issue. Referrer definitely works on other iPhones including older models so I'm not sure that that's it.

Huh, I distinctly remember having this problem because referrer wasn't passed. Then again, it was years ago, so maybe they added it since then.

Munkeymon
Aug 14, 2003

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



Lumpy posted:

Huh, I distinctly remember having this problem because referrer wasn't passed. Then again, it was years ago, so maybe they added it since then.

I remember using referrer to let customers pass options to our integration iframes five years ago and I'm pretty sure we tested it on iOS.

Rosalind
Apr 30, 2013

When we hit our lowest point, we are open to the greatest change.

Just to not leave people hanging I think I discovered the issue and it's not Javascript-related, or at least not related to any Javascript I wrote. Our person responsible for the website (not her main job) used Wix to make the site. It's apparently a known issue that Wix behaves oddly or even doesn't work entirely on older iPhones. We're going to explore migrating to some other site builder that promises backward compatibility although apparently Apple recently stopped providing support for iPhone 5 series phones. Anyways, thank you all for your help!

Ranzear
Jul 25, 2013


quote:

Available: September 21, 2012
Discontinued: September 10, 2013
Tell them they bought an Apple device, they were supposed to throw it away for the new one years ago.

I think when official support ends, so should yours.

Rosalind
Apr 30, 2013

When we hit our lowest point, we are open to the greatest change.

Ranzear posted:

Tell them they bought an Apple device, they were supposed to throw it away for the new one years ago.

I think when official support ends, so should yours.

I work in health research and we need to be able to accommodate participants who might have older phones unfortunately otherwise I'd wholeheartedly agree!

Ranzear
Jul 25, 2013

Yeah that's fair. I used to redirect IE users to the Chrome download page when they didn't have Canvas and IE6 users to that 'IE6 is dead, please move on' page.

Ranzear fucked around with this message at 23:44 on Oct 13, 2017

Dross
Sep 26, 2006

Every night he puts his hot dogs in the trees so the pigeons can't get them.

Crossposting from the horrors thread because maybe it's not a horror?

dev bootcamp instructor posted:



JavaScript code:
const promisesExample = () => {
  return new Promise((resolve, reject) => {
    $.ajax("someExampleUrl")
      .done((data) => {
        resolve(data);
      })
      .fail((error) => {
        reject(error);
      });
  });
};

This is how I'm being taught to do promises, and I feel like it's unnecessary because ajax already returns a promise so you're just unnecessarily wrapping a promise in another one with no data transformation happening. Is there some benefit to this?

Maluco Marinero
Jan 18, 2001

Damn that's a
fine elephant.
It would be far better demonstrated if the JQuery was ditched for XMLHttpRequest or fetch. I'm not sure if JQuery's Ajax function actually return a compliant promise because I haven't used it for so long, but yes, using promises without transformation is meaningless obfuscation. The purpose of promises is two fold, as a writer of promise return code, its providing a consistent API for async code that can be arranged in all sorts of manner, as a consumer of promise code, it's being able to work with the results of that asynchronous computation like they were values, so you can perform maps, transformations, etc without having to think too hard about the asynchronous bit.

The example above a shows the API with none of the why.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Rosalind posted:

I work in health research and we need to be able to accommodate participants who might have older phones unfortunately otherwise I'd wholeheartedly agree!

I have to support state and county level government computers, weep for my minimum specs.
On the plus side, I did convince sales that new contracts starting in 2018 have to use "modern" browsers as defined by Microsoft (Edge, not IE). How well that'll work, we'll see, but at least I can tell them "I told you so". And then go add backwards support.
Ironically we did have one state that delayed deployment because, while we worked in the latest browsers, a sister software install didn't and would need some time to resolve the issues.

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Maluco Marinero posted:

It would be far better demonstrated if the JQuery was ditched for XMLHttpRequest or fetch. I'm not sure if JQuery's Ajax function actually return a compliant promise because I haven't used it for so long, but yes, using promises without transformation is meaningless obfuscation. The purpose of promises is two fold, as a writer of promise return code, its providing a consistent API for async code that can be arranged in all sorts of manner, as a consumer of promise code, it's being able to work with the results of that asynchronous computation like they were values, so you can perform maps, transformations, etc without having to think too hard about the asynchronous bit.

The example above a shows the API with none of the why.

I'm almost positive that jQuery 3's big thing was ditching their wrap around code and just using native promises and such. The rest, yes.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dross posted:

Crossposting from the horrors thread because maybe it's not a horror?


This is how I'm being taught to do promises, and I feel like it's unnecessary because ajax already returns a promise so you're just unnecessarily wrapping a promise in another one with no data transformation happening. Is there some benefit to this?

jQuery's Ajax is not a "real" promise, so if you need an actual Promise conforming solution, you'd so something sort of along those lines. But that is a very odd way of trying to teach someone promises. In fact, it may be the worst way I could think of.

Tomorrow, I will post links I have bookmarked about promises that I found helpful when I'm at a computer. They aren't really that complicated, but there are a few gotchas.

FYI, the "modern" way to do that example is with the native fetch API, which does actually return a real promise:

JavaScript code:
fetch( someURL )
.then( result => console.log("I got a result!", result) )
.catch( error => console.error("oh noes!", error) );

Dross
Sep 26, 2006

Every night he puts his hot dogs in the trees so the pigeons can't get them.

ajax can chain .then and .catch off of it like a real promise (in addition to the original .done and .fail), and be included in a promise.all array. What other differences would there be to look out for?

I've only been doing JS for about two months but I think I have a pretty good grasp on how to think in terms of data transformations as opposed to imperatively. Which makes me chafe at the fact that we're being taught imperatively. I study in my free time too so sometimes we'll be getting taught something and I'm thinking "I already know a much better way to do this" which is probably Coding Newbie Trap Alpha.

edit: I think jQuery 3.0 made deferred objects fully compatible with the ES6 native promise API unless I'm misreading/misunderstanding something.

Dross fucked around with this message at 05:20 on Oct 19, 2017

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Dross posted:

ajax can chain .then and .catch off of it like a real promise (in addition to the original .done and .fail), and be included in a promise.all array. What other differences would there be to look out for?

I've only been doing JS for about two months but I think I have a pretty good grasp on how to think in terms of data transformations as opposed to imperatively. Which makes me chafe at the fact that we're being taught imperatively. I study in my free time too so sometimes we'll be getting taught something and I'm thinking "I already know a much better way to do this" which is probably Coding Newbie Trap Alpha.

edit: I think jQuery 3.0 made deferred objects fully compatible with the ES6 native promise API unless I'm misreading/misunderstanding something.

I haven’t used jQuery in a long time, so it is quite possible that it is actually using Promises now. I’ve been doing JS for almost as long as it has existed so sometimes my knowledge is from what I remember from using something 10+ years ago....

Ranzear
Jul 25, 2013

Let's be clear to at least two people now in the past week or so: You're being taught JQuery, not Javascript.

Dross
Sep 26, 2006

Every night he puts his hot dogs in the trees so the pigeons can't get them.

I was taught vanilla JavaScript before we incorporated Jquery. They just held off on teaching us promises until we could use them in a really stupid way I guess

huhu
Feb 24, 2006
Shot in the dark but...

My npm start script:
code:
    "start": "webpack-dev-server",
when run in Pycharm in debug mode results in

code:
/usr/local/bin/node /usr/local/lib/node_modules/npm/bin/npm-cli.js start

> foo@0.2.0 start /Users/fizz/Documents/bar
> webpack-dev-server

Project is running at [url]http://localhost:3000/[/url]
webpack output is served from [url]http://localhost:3000/build/[/url]
404s will fallback to /index.html

Process finished with exit code 0
Thoughts? My Google results thus far have been unsuccessful.

Dogcow
Jun 21, 2005

huhu posted:

Shot in the dark but...

My npm start script:
code:
    "start": "webpack-dev-server",
when run in Pycharm in debug mode results in

code:
/usr/local/bin/node /usr/local/lib/node_modules/npm/bin/npm-cli.js start

> foo@0.2.0 start /Users/fizz/Documents/bar
> webpack-dev-server

Project is running at [url]http://localhost:3000/[/url]
webpack output is served from [url]http://localhost:3000/build/[/url]
404s will fallback to /index.html

Process finished with exit code 0
Thoughts? My Google results thus far have been unsuccessful.

Can you try the verbose flag to maybe get more info?
Shell session code:
npm run start —verbose

Thermopyle
Jul 1, 2003

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

huhu posted:

when run in Pycharm in debug mode results in

It's been a long time since I worked through Pycharm like this so I can't exactly help you, but I long ago moved to just running my dev server in a separate terminal. Just works nicer.

Odette
Mar 19, 2011

Thermopyle posted:

It's been a long time since I worked through Pycharm like this so I can't exactly help you, but I long ago moved to just running my dev server in a separate terminal. Just works nicer.

The only time I'd consider running in IntelliJ derived IDEs is when debugging.

huhu
Feb 24, 2006

Dogcow posted:

Can you try the verbose flag to maybe get more info?
Shell session code:
npm run start —verbose

code:
/usr/local/bin/node /usr/local/lib/node_modules/npm/bin/npm-cli.js start -verbose
npm info it worked if it ends with ok
npm verb cli [ '/usr/local/bin/node',
npm verb cli   '/usr/local/lib/node_modules/npm/bin/npm-cli.js',
npm verb cli   'start',
npm verb cli   '-verbose' ]
npm info using npm@5.4.2
npm info using node@v6.11.1
npm verb run-script [ 'prestart', 'start', 'poststart' ]
npm info lifecycle foo@0.2.0~prestart: foo@0.2.0
npm info lifecycle foo@0.2.0~start: foo@0.2.0

> foo@0.2.0 start /Users/foo/Documents/foo
> webpack-dev-server

Project is running at [url]http://localhost:3000/[/url]
webpack output is served from [url]http://localhost:3000/build/[/url]
404s will fallback to /index.html
npm verb lifecycle foo@0.2.0~start: unsafe-perm in lifecycle true
npm verb lifecycle foo@0.2.0~start: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/Users/foo/Documents/foo/node_modules/.bin:/Users/foo/bin:/Library/PostgreSQL/9.6/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/foo/Library/Android/sdk/tools:/Users/foo/Library/Android/sdk/platform-tools
npm verb lifecycle foo@0.2.0~start: CWD: /Users/foo/Documents/foo
npm info lifecycle foo@0.2.0~poststart: foo@0.2.0
npm verb exit [ 0, true ]
npm info ok 

Process finished with exit code 0
I'm doing a demo of Pycharm for some coworkers and I was hoping to be able to get React running from within to show them debugging; also because I've never tried it.

Thermopyle
Jul 1, 2003

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

Speaking of debugging with Jetbrains IDEs...

You can now use the browser <> IDE Javascript debugging with Chrome while DevTools is open. This is big news!

https://developers.google.com/web/updates/2017/10/devtools-release-notes#multi-client

In case you aren't aware of what I'm talking about you can set breakpoints in your code in your IDE, and when the browser hits those breakpoints it breaks in your IDE where you can inspect variables and all the other stuff you do while debugging.

Alligator
Jun 10, 2009

LOCK AND LOAF

huhu posted:

code:
snip
I'm doing a demo of Pycharm for some coworkers and I was hoping to be able to get React running from within to show them debugging; also because I've never tried it.
FYI that --verbose is going to npm not webpack-dev-server. If you want to pass an argument to the thing npm is running you would need an extra set of hyphens: npm run start -- --verbose.

You don't have quiet or noInfo set to true in your webpack config do you?

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
I hate for loops. I think for the most part a for loop is better replaced by something more modern, .forEach, .some etc.

However I have a for loop that tries to find the first element match and then returns out of the function.

Trying to do the same with a for each is impossible because returning in a foreach just causes the foreach to begin parsing the next element, it doesn't return at the higher scope.

Is there a better way to do this other than using a for loop?

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Knifegrab posted:

I hate for loops. I think for the most part a for loop is better replaced by something more modern, .forEach, .some etc.

However I have a for loop that tries to find the first element match and then returns out of the function.

Trying to do the same with a for each is impossible because returning in a foreach just causes the foreach to begin parsing the next element, it doesn't return at the higher scope.

Is there a better way to do this other than using a for loop?

If you are using TypeScript, you can use the ES6 for...of loop in ES5. If you are using ES6... use for...of.

There are also things like lodash.find, which does exactly what you want.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Skandranon posted:

If you are using TypeScript, you can use the ES6 for...of loop in ES5. If you are using ES6... use for...of.

There are also things like lodash.find, which does exactly what you want.

Unfortunately I cannot use find or for of because I am comparing each element in two different arrays, so of would only give me the element of one array. Similar reasons for find, since find would only return the found element (that is different) but cannot tell me how they differ.

For in also would not work because it does not respect order (it iterates based on when the particular key was added not the value of the key).

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

I hate for loops. I think for the most part a for loop is better replaced by something more modern, .forEach, .some etc.

However I have a for loop that tries to find the first element match and then returns out of the function.

Trying to do the same with a for each is impossible because returning in a foreach just causes the foreach to begin parsing the next element, it doesn't return at the higher scope.

Is there a better way to do this other than using a for loop?

JavaScript code:

let poop = false;
try {
  someArray.foreach( _item => {
     if (_item === 'blah) {
        let poop = _item;
        throw Error
     }
  })
} catch (e) {
  // omg, this is hacky
}
:v:

EDIT: you can also use .find() to return the first match in an array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

EDIT2: Oh you said you can't use find... :smith:

Lumpy fucked around with this message at 18:30 on Oct 25, 2017

Skandranon
Sep 6, 2008
fucking stupid, dont listen to me

Knifegrab posted:

Unfortunately I cannot use find or for of because I am comparing each element in two different arrays, so of would only give me the element of one array. Similar reasons for find, since find would only return the found element (that is different) but cannot tell me how they differ.

For in also would not work because it does not respect order (it iterates based on when the particular key was added not the value of the key).

I don't see how for..of can't work where you imagine forEach would, but if not, no, there are no other options.

Edit: Yeah, do the above thing, that's a great idea.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
My assumption going into this was that a standard for loop is my best bet, I was just curious if there was some other means I wasn't seeing. I don't like for loops, for reasons I can't articulate but I am fine with it, I would prefer to do it right than hacky and yeah I knew about the throw approach *barfs intensly* .

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

My assumption going into this was that a standard for loop is my best bet, I was just curious if there was some other means I wasn't seeing. I don't like for loops, for reasons I can't articulate but I am fine with it, I would prefer to do it right than hacky and yeah I knew about the throw approach *barfs intensly* .

I suspect that there is some XY Problem here. Can you share a bit more code to see if there is a better way to approaching the end goal?

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Lumpy posted:

I suspect that there is some XY Problem here. Can you share a bit more code to see if there is a better way to approaching the end goal?

Sure, its just a really really simple bit of code to help sort IP addresses.

code:
    Ip(a, b) {
        a = a.split('.');
        b = b.split('.');

        if (a.length > b.length) {
            return 1;
        } else if (a.length < b.length) {
            return -1;
        }

        for (let i = 0; i < a.length; i++) {
            if ((a[i] = parseInt(a[i], 10)) > (b[i] = parseInt(b[i], 10))) {
                return 1;
            } else if (a[i] < b[i]) {
                return -1;
            }
        }
        return 0;
    }

Munkeymon
Aug 14, 2003

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



JavaScript code:
valueArray.reduce((acc, cur) => acc.found
  ? return acc
  : cur != acc.last
    ? return {found: true, last: cur}
    : return {found: false, last: cur}
  , {found: false, last: NaN}).last
Enjoy the nightmares :v:

e: oh, yeah, that'd be more annoying

Might be more performant to map them to eg {padded: '004.004.004.008', original: '4.4.4.8'}, sort them based on simple string comparison and then map them back to the original value.

Munkeymon fucked around with this message at 18:46 on Oct 25, 2017

Capri Sun Tzu
Oct 24, 2017

by Reene

Knifegrab posted:

My assumption going into this was that a standard for loop is my best bet, I was just curious if there was some other means I wasn't seeing. I don't like for loops, for reasons I can't articulate but I am fine with it, I would prefer to do it right than hacky and yeah I knew about the throw approach *barfs intensly* .
Hey, I also hate for loops and the reason why is because it's harder to tell at a glance what the code is doing especially when you start nesting them! You could possibly use array.map or array.filter instead of find but it would be helpful if you'd show some more code to help us understand what you'd be filtering on.

necrotic
Aug 2, 2005
I owe my brother big time for this!
Gross, mutating the array while iterating it.

In other news, turns out embedding React into an Ember app is super easy. This excites me.

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

necrotic posted:

Gross, mutating the array while iterating it.

In other news, turns out embedding React into an Ember app is super easy. This excites me.

Since the array is never passed anywhere or returned in anyway I think its cool and good. :colbert:

necrotic
Aug 2, 2005
I owe my brother big time for this!
At least stop shadowing the arguments. You'll drive me mad! Maybe that's the goal?

Adbot
ADBOT LOVES YOU

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Knifegrab posted:

Since the array is never passed anywhere or returned in anyway I think its cool and good. :colbert:

If you're going to mutate, why not go nuts!:

JavaScript code:
Ip(a, b) {

  // your stuff....
  a = a.split('.');
  b = b.split('.');
  if (a.length > b.length) {
     return 1;
  } else if (a.length < b.length) {
    return -1;
  }

  // terrible new stuff!
  while( a.length > 0 ) {
    let _a = parseInt( a.pop() ) ;
    let _b = parseInt( b.pop() );
    if( _a > _b ) return 1;
    if( _b > _a ) return -1;
  }
  return 0;
}

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