These are chat archives for FreeCodeCamp/HelpJavaScript

13th
Mar 2018
Ryan Williams
@Ryanwfile
Mar 13 2018 02:47
Can someone please help me with this div background image moving, the image moves as text inserted from javascript appears and I just want the image to stay still, also the site is done in wordpress any help is greatly appreciated https://codereese.com/
Long Nguyen
@longnt80
Mar 13 2018 06:03
is chaining methods better for performance?

this:

target.setAttribute('data-x', x).setAttribute('data-y', y);

vs

target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
Markus Kiili
@Masd925
Mar 13 2018 06:21
@longnt80 I would guess that chaining is faster because there are less operations. Usually you can avoid such optimizations and concentrate on readability.
Long Nguyen
@longnt80
Mar 13 2018 06:35
@Masd925 thanks
CamperBot
@camperbot
Mar 13 2018 06:35
longnt80 sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4724 | @masd925 |http://www.freecodecamp.org/masd925
Fabien SHAN
@X140hu4
Mar 13 2018 06:46
@Ryanwfile You mean the paralax effect?
sabahatullah
@sabahatullah
Mar 13 2018 11:49
hi there, for an element, if we have different background image url under media queries, can we return all of the them with javascript
for example a div has a background image that changes dependant on the screen size. If I want to fetch all the images urls under various media queries, Any idea how that can be done?
Marianissimus
@Marianissimus
Mar 13 2018 11:57
@sabahatullah mhm, interesting problem, but why do you want to do that? the current background is not enough for js?
sabahatullah
@sabahatullah
Mar 13 2018 12:01
@Marianissimus na we need all images. I have a work around using resize function but I was wondering since the media queries are technically part of the DOM I should be able to grab all the images . isn't it
Marianissimus
@Marianissimus
Mar 13 2018 12:02
I will google it, but I doubt it: since the DOM is loaded first before your js loads, and since you load only 1 image via your media query, only that image can be then selected and manipulated in javascript
sabahatullah
@sabahatullah
Mar 13 2018 12:21
so I think the main question we need to address here is that does browser treat all media query rules as DOM elements. I am under the impression all the media query rules are part of DOM so there should be a way to return that with javascript.
Markus Kiili
@Masd925
Mar 13 2018 12:29
@sabahatullah Are you talking about preloading images, or something else?
Adel
@AdelMahjoub
Mar 13 2018 12:38
@Ryanwfile if it is a bout the text animations is triggered before the image is loaded, you can wait for the image to load then trigger the text animation. while waiting for the image to load, you can use a canvas and draw a placeholder of the same image size.
sabahatullah
@sabahatullah
Mar 13 2018 12:49
@Masd925 not preloading images. just get/return the all the image urls with javascript of one element with the prespective that the URL changes because of the media query for different screens
Adel
@AdelMahjoub
Mar 13 2018 12:49
@sabahatullah the code below is to generate different background image for different classes, based on one spritesheet. you can pack all your images in one spritesheet, load it once, and set the background on each media query using x and y positions
//Entities tiles / sprites
@each $entity, $code in $tile-code {
  $x: floor($code % $tile-sheet-columns) * $tile-size; //x position in the sprite tile-sheet
  $y: floor($code / $tile-sheet-columns) * $tile-size; //y position in the sprite tile-sheet
  .tile-#{$entity} {
    @include tile;
    background:
      url($tile-sheet)
      no-repeat 
      floor(-$x) 
      floor(-$y);
  }
}
@sabahatullah if there is not a lot of images, no need to generate classes using scss, you can hardcode each position
Markus Kiili
@Masd925
Mar 13 2018 12:51
@sabahatullah You wan't to get the url's from the css file using JS?
Adel
@AdelMahjoub
Mar 13 2018 12:52
@sabahatullah as @Masd925 suggested, it is easier done using javascript and an on resize event
Markus Kiili
@Masd925
Mar 13 2018 12:53
@AdelMahjoub :+1:
There is a way to access CSS stylesheets with JS, but not a good idea generally.
Makopa
@makopa
Mar 13 2018 13:12
Goodday everyone i have basic JS questions . why the method sayHello does not work and sayGoodbye is working fine. using this.name. my understanding is that both method declaration is the same
let person = {
  name: 'Jordan',
  sayHello : () => this.name,
  sayGoodbye(){
    return 'Goodbye ' + this.name;
  }
};
Abdullah
@AbdullahChaudhry
Mar 13 2018 13:16
@makopa You are using a fat arrow which is changing the binding of the 'this' keyword
let person = {
  name: 'Jordan',
  sayHello : function() {
    return this.name
    },
  sayGoodbye(){
    return 'Goodbye ' + this.name;
  }
};
^^ this works
Makopa
@makopa
Mar 13 2018 13:17
i see ill check into that @AbdullahChaudhry thank you
CamperBot
@camperbot
Mar 13 2018 13:17
makopa sends brownie points to @abdullahchaudhry :sparkles: :thumbsup: :sparkles:
:cookie: 310 | @abdullahchaudhry |http://www.freecodecamp.org/abdullahchaudhry
Makopa
@makopa
Mar 13 2018 13:20
it returns undefined so basically cant use this on fat arrow syntax inside an object
Abdullah
@AbdullahChaudhry
Mar 13 2018 13:21
let person = {
  name: 'Jordan',
  sayHello : () => {
    console.log('this:', this)
    return this.name
    },
  sayGoodbye(){
    return 'Goodbye ' + this.name;
  }
};

let person2 = {
  name: 'Jordan',
  sayHello : function() {
    console.log('this:', this)
    return this.name
    },
  sayGoodbye(){
    return 'Goodbye ' + this.name;
  }
};

console.log('person2.sayHello():', person2.sayHello())
console.log('person.sayHello():', person.sayHello())
Using a fat arrow will change the reference for 'this'. It will overwrite the 'this' reference, in this context the 'this' keyword is not referencing the person object, it is referencing the console (or global window object).
So when we invoke person.sayHello(), the 'this' keyword is referencing the global window object, and it can't find the name variable so it returns undefined
Makopa
@makopa
Mar 13 2018 13:26
i see. even the "this" next to return statement will reference to the global scope on person object
??
Markus Kiili
@Masd925
Mar 13 2018 13:28
@AbdullahChaudhry There is always a name property on the global object, but that is besides the point here.
Makopa
@makopa
Mar 13 2018 13:29
let person = {
  name: 'Jordan',
  sayHello : () => {
    console.log(person.name);
    }
};
this works as expected i used the object name to reference the name in person object
Returns undefined^^
Makopa
@makopa
Mar 13 2018 13:30
'this' keyword is really confusing hehee. thanks fellas for the help!
Abdullah
@AbdullahChaudhry
Mar 13 2018 13:30
@makopa That works because you aren't using the 'this' keyword to reference name which is inside the person object
@makopa It won't find name inside sayHello function, so then it will look outside of it and find it in the person object. That's why that works
Markus Kiili
@Masd925
Mar 13 2018 13:31
@AbdullahChaudhry It is different in node and editors like that are not reliable. If you try it is a browser JS, you will see that the name property of the window object holds a string.
Abdullah
@AbdullahChaudhry
Mar 13 2018 13:31
actually that's wrong . sorry.
You are directly referencing person object, and then accessing the name attribute
Makopa
@makopa
Mar 13 2018 13:32
alright! its clear now. ill take a read on fat arrow function. im not familiar with its behavior thanks! fat arrow is still es6 right?
@AbdullahChaudhry
CamperBot
@camperbot
Mar 13 2018 13:32
makopa sends brownie points to @abdullahchaudhry :sparkles: :thumbsup: :sparkles:
api offline
Abdullah
@AbdullahChaudhry
Mar 13 2018 13:32
@Masd925 Just pointing out that nuance
Markus Kiili
@Masd925
Mar 13 2018 13:32
@AbdullahChaudhry Yeah.
Abdullah
@AbdullahChaudhry
Mar 13 2018 13:33
@Masd925 I just opened chrome dev tools console, this.name returns ""
Markus Kiili
@Masd925
Mar 13 2018 13:33
@AbdullahChaudhry Yes.
Abdullah
@AbdullahChaudhry
Mar 13 2018 13:33
:+1:
Yes, ES6
Markus Kiili
@Masd925
Mar 13 2018 13:34
Using name leads to nice bugs:
Abdullah
@AbdullahChaudhry
Mar 13 2018 13:34
Thanks @Masd925
CamperBot
@camperbot
Mar 13 2018 13:34
abdullahchaudhry sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4727 | @masd925 |http://www.freecodecamp.org/masd925
Leigh Hobson
@leighhobson89
Mar 13 2018 13:34
Hi guys, is there anything syntactically incorrect with this statement?
$("div[id='" + user[1] + "']").css(".background-image", "url('" + bgImage + "')");
Markus Kiili
@Masd925
Mar 13 2018 13:34
var name = {};
console.log(name); // "[object Object]"
Makopa
@makopa
Mar 13 2018 13:48
let restaurant = {
  _name: 'Italian Bistro',
  _seatingCapacity: 120,
  _hasDineInSpecial: true,
}
is the underscore "_" is just a naming convention right?
Marianissimus
@Marianissimus
Mar 13 2018 13:53
@leighhobson89 this. this must be it: (".background-image // the dot before background-image. I guess that's it
Abdullah
@AbdullahChaudhry
Mar 13 2018 13:53
@makopa yeah
sabahatullah
@sabahatullah
Mar 13 2018 14:06
@Masd925 yes background image urls
Leigh Hobson
@leighhobson89
Mar 13 2018 14:18
@Marianissimus thanks
CamperBot
@camperbot
Mar 13 2018 14:18
leighhobson89 sends brownie points to @marianissimus :sparkles: :thumbsup: :sparkles:
:cookie: 482 | @marianissimus |http://www.freecodecamp.org/marianissimus
Jason Luboff
@JLuboff
Mar 13 2018 15:13
:wave:
Dardan Demiri
@dardandmr
Mar 13 2018 15:28
@camperbot
Leigh Hobson
@leighhobson89
Mar 13 2018 17:39

afternoon campers - any ideas why the background image isnt showing based off of this code? dataArray[0] contains the hyperlink.

function stringParser(user, status, dataArray) {

  $("#userheader").append(
    "<div class='row justify-content-md-center userrecords'><div class='col-xs-3 thumbnail'><img src='" +
      user[0] +
      "' class='img-circle' alt='" + user[1] + "'></img></div><div id='statusColumn' class='" +
      status +
      " col-xs-1'></div><div id='" + user[1].toLowerCase() + "'class='col-xs-8'><div class='row justify-content-md-center'><p>" +
      user[1] +
      "</p></div><div class='row justify-content-md-center'><p>" + dataArray[1] + "</p></div></div>"
  ).then(function() {

    $("div[id='" + user[1].toLowerCase + "']").css("background-image", "url('" + dataArray[0] + "')");
    });
}

the variables used are passed through these functions:

function outputUsers(users, url, urlSection, selection) {
        var dataArray = [];
  users.forEach(function(user) {
    $.getJSON(url + urlSection[1] + user[1]).then(function(response) {

      if (response.stream) {
          var bgImage = response.stream.preview.medium;
          var game = response.stream.game;  
          dataArray.push(bgImage, game);
        //if online
        processOnlineUsers(user, url, urlSection, selection, dataArray);
      } else {
        dataArray.push(bgImage, "User currently Offline");
        processOfflineUsers(user, url, urlSection, selection, dataArray);
      }
    });
  });
}

function processOnlineUsers(user, url, urlSection, selection, dataArray) {
  var status = "onlinestatus";
  $.getJSON(url + urlSection[0] + user[1]).then(function(data) {
    user[0] = data.logo;
    if (selection == 0) {
      return; //skip if "Offline"
    }
    stringParser(user, status, dataArray);
  });
}
URL i mean, not hyperlink
Jason Luboff
@JLuboff
Mar 13 2018 17:42
Becuase dataArray[0] has multiple elements
Actually scratch that
Actually, no, that might be part of the issue. dataArray doesn't reset each loop, so dataArray[0] will always be the first user element
Leigh Hobson
@leighhobson89
Mar 13 2018 17:44
lowerCase has no brackets
ill try that too
if that was the case id get 1 image in all divs, right?
the same one
brackets did nothing btw
i could move it into the loop to initialise ie reset, but im getting no images at all. is something wrong with the syntax for changing the css?
moved it, that did nothing, must be sopmething to do with the async call
Jason Luboff
@JLuboff
Mar 13 2018 17:48

@leighhobson89 Try this

....
.then(function() {
console.log(dataArray);
    $("div[id='" + user[1].toLowerCase + "']").css("background-image", "url('" + dataArray[0] + "')");
    });

Whats in dataArray according to the console?

Leigh Hobson
@leighhobson89
Mar 13 2018 17:51
this error is appearing since i added the then() (i had my css setter command without a then before and didnt get these errors but zstill no bg image appearing so figuired i needed it to handle the async
image.png
Jason Luboff
@JLuboff
Mar 13 2018 17:53
I'm guessing append does not return a promise thus doesn't allow .then()
Leigh Hobson
@leighhobson89
Mar 13 2018 17:53
if i log before the parse ie at the top of the function i get this
image.png
so the offline ones return undefined and the online ones return their link
ahh
i wonder how to implement it then? :/
Jason Luboff
@JLuboff
Mar 13 2018 17:55
I don't think there is really a reason you would need to use a promise there
Leigh Hobson
@leighhobson89
Mar 13 2018 17:57
i took the then out and now im getting something for the online ones
think ill be ok now, i will put a static image in for the offline ones
Jason Luboff
@JLuboff
Mar 13 2018 17:57
:+1:
Leigh Hobson
@leighhobson89
Mar 13 2018 17:58
turns out it would have worked before i put the then in if it werent for the .toLowerCase not having brackets. simple syntax error
cheers anyway
Jason Luboff
@JLuboff
Mar 13 2018 17:58
That'll happen
Jason Luboff
@JLuboff
Mar 13 2018 18:08
@alpox just giving you more brownies, thanks
CamperBot
@camperbot
Mar 13 2018 18:08
jluboff sends brownie points to @alpox :sparkles: :thumbsup: :sparkles:
:star2: 1587 | @alpox |http://www.freecodecamp.org/alpox
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:16
hello everyone
Jason Luboff
@JLuboff
Mar 13 2018 21:16
Yo
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:17
all good?
Jason Luboff
@JLuboff
Mar 13 2018 21:17
I'd say so. You?
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:17
good to hear, same here :D
can you try to give me an help? been trying to figure out how to refresh a token using a package that was builted to make easier and simpler to use spotify api
here's the one
you are forced at certain moment to refresh the token or you lose acess
Jason Luboff
@JLuboff
Mar 13 2018 21:19
Sounds just like the Office 365 API... forced to do a token refresh aka log in again
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:19
ahahha something close to that I would say then
Markus Kiili
@Masd925
Mar 13 2018 21:21
:wave:
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:22
hey @Masd925 how's the new job going?
Markus Kiili
@Masd925
Mar 13 2018 21:22
@tiagocorreiaalmeida Starts in 10 weeks just before summer.
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:23
right in time for the usual shorts outfit then :D
Markus Kiili
@Masd925
Mar 13 2018 21:23
@tiagocorreiaalmeida I think that I have to buy some decent clothes now.
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:26
aaa crap :D
Jason Luboff
@JLuboff
Mar 13 2018 21:38
@Masd925 Dang, 10 weeks?!
@tiagocorreiaalmeida Btw, I never found a solution for that lol
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:39
yeah here they give an example let me shwo it to you
but gets med confused where should I proceed to do the call
Markus Kiili
@Masd925
Mar 13 2018 21:40
@JLuboff Working 5 weeks on the old job making animations and then most likely 5 weeks of vacation before the new job starts. Time to learn clojure and emacs then.
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:40
async function setSpotifyAccessToken() {
    try {
        let data = await spotifyApi.clientCredentialsGrant();
        spotifyApi.setAccessToken(data.body["access_token"]);
        spotifyApi.setRefreshToken(data.body["refresh_token"]);
    } catch (e) {
        console.log(e);
    }
}
this is the code I use to set the initial token
they refer that after a certain time the token needs to be refreshed
// clientId, clientSecret and refreshToken has been set on the api object previous to this call.
spotifyApi.refreshAccessToken()
  .then(function(data) {
    console.log('The access token has been refreshed!');

    // Save the access token so that it's used in future calls
    spotifyApi.setAccessToken(data.body['access_token']);
  }, function(err) {
    console.log('Could not refresh access token', err);
  });
something like this
Jason Luboff
@JLuboff
Mar 13 2018 21:40
@Masd925 5 weeks of vacation? Nice!
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:40
not sure where I should be calling it
Markus Kiili
@Masd925
Mar 13 2018 21:41
@JLuboff That is standard in Finland.
Jason Luboff
@JLuboff
Mar 13 2018 21:41
@tiagocorreiaalmeida Does the user frequently change pages or stay on the same page? You may need to create a timer of some sort?
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:42
I only call the api to make an onkeypress request to the database this is used to create a post in the database, the big issue with testing any change is that this sometimes takes 2 hours to lose the token expiration :D
Jason Luboff
@JLuboff
Mar 13 2018 21:42
@Masd925 ...well la de da. I get a whooping 2 weeks
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:43
yeah it last's one hour just console logged it
would make sense to call if it the code above trhow's an error on the catch?
Jason Luboff
@JLuboff
Mar 13 2018 21:44
So.. you need to create a timer I guess? I'm not really sure
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:44
I tried something similiar to that didnt went any far
Jason Luboff
@JLuboff
Mar 13 2018 21:44
You need someone smarter than me :P
It took me a week to break out all my SQL queries from my routes page lol
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:45
well it all depends of the time you used on it can be a week with 30minutes a day :D
Markus Kiili
@Masd925
Mar 13 2018 21:45
@JLuboff I have been looking for some real language to learn, and it is probable that the new firm will use clojure on the first two months learning period.
Jason Luboff
@JLuboff
Mar 13 2018 21:45
Couple of hours a day (minus the weekends). Given, I was having trouble with my promises
@AdelMahjoub Stop giving yourself fake brownies and see if you can help @tiagocorreiaalmeida above
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:46
^
Jason Luboff
@JLuboff
Mar 13 2018 21:47
@Masd925 Well 5 weeks of no work will give you a good chunk oftime to do so
Adel
@AdelMahjoub
Mar 13 2018 21:47
:information_desk_person: ok !
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:47
hey there @AdelMahjoub .D
:D
Adel
@AdelMahjoub
Mar 13 2018 21:47
@tiagocorreiaalmeida that's mean I need to read spotify docs
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:48
@AdelMahjoub no :D
there's a tested package that was builted to use the api its all refered in the spotify api website to use this package on node
im a bit confused with a situation
    spotifyApi = new SpotifyWebApi({
        clientId: process.env.SPOTIFY_ID,
        clientSecret: process.env.SPOTIFY_KEY
    });


async function setSpotifyAccessToken() {
    try {
        let data = await spotifyApi.clientCredentialsGrant();
        spotifyApi.setAccessToken(data.body["access_token"]);
        spotifyApi.setRefreshToken(data.body["refresh_token"]);
        console.log('The token expires in ' + data.body['expires_in']);
    } catch (e) {
        console.log(e);
    }
}

setSpotifyAccessToken();
this is how I set up the api connection it last's 3600 seconds per token, im a bit lost where should I refresh the token
Adel
@AdelMahjoub
Mar 13 2018 21:51
@tiagocorreiaalmeida store the first token you get, using node-cache for example. On each request to spotify use that token, on failure / token expired => refresh the token => request again, on success => all is green no need to refresh the token
@tiagocorreiaalmeida you can create a function that request=>update token if necessary , and call it whenever you need to hit spotify api
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:53
in other words call the function I Have above on the route I need it to be used?
Adel
@AdelMahjoub
Mar 13 2018 21:53
@tiagocorreiaalmeida unless I'm on the west and did not understood :laughing:
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:53
so every time the route is requested I call th efunction I have
I guess?:D
Adel
@AdelMahjoub
Mar 13 2018 21:54
@tiagocorreiaalmeida if the token is expired you get a response error right ?
@tiagocorreiaalmeida only update the token if you get an error, or check the lifetime
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:54
yeah indeed I tried this
router.get(/(.+)/, auth, async (req, res) => {
    let albumName = req.params[0];
    try {
        let apiResponse = await spotifyApi.searchAlbums(albumName, {
            limit: 3
        });
        if (apiResponse.body.albums.items.length == 0)
            return res.error(409, "No results found based on your search!");
        let dataClean = apiResponse.body.albums.items.map(ele => ({
            albumName: ele.name,
            albumLink: ele.external_urls.spotify,
            thumbnail: ele.images[2].url,
            albumCover: ele.images[0].url,
            artists: ele.artists.map(artist => ({
                name: artist.name,
                link: artist.external_urls.spotify
            }))
        }));
        res.send(dataClean);
    } catch (e) {
        if (e.statusCode == 401 && e.name == "WebapiError") {
            return spotifyApi.refreshAccessToken()
                .then((data) =>
                    spotifyApi.setAccessToken(data.body['access_token']));
        }
        res.error(
            500,
            "Something went wrong please refresh the page and try again",
            e
        );
    }
});
probably missed some proprety cause this didnt worked :\
Adel
@AdelMahjoub
Mar 13 2018 21:57
@tiagocorreiaalmeida you need to make the request again on error, better extract all that code in a separate middleware
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:58
still this should work I think? ofcourse wouldnt work for the current request but the one after should?
Adel
@AdelMahjoub
Mar 13 2018 21:58
@tiagocorreiaalmeida I remember handled this same situation somewhere, 2sec
Moisés Man
@moigithub
Mar 13 2018 21:59
what res.error does.. (dont remember)
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 21:59
@moigithub its a middleware function that sends a response normally with the status code and message I pass by in this case I also pass the error that I store on a log file
in others words res.status(500).send("...")
Leigh Hobson
@leighhobson89
Mar 13 2018 22:00

from the top level, there is a function call, with another function call inside that. In this third function there is a variable that I want accessible to the top area, Can some kind person give me the syntax to do that? In php you assign a variable to the result of the function return but when its a few layers deep i dont really get what to do. to illustrate:

selectMenuItem(users, url, urlSection, 2);

calls:

function selectMenuItem(users, url, urlSection, menu) { //change color of selected menu and parse out users.
  switch (menu) {
    case 0:
      $("#all, #online").removeClass("menuselected").addClass("menu"); 
      $("#offline").removeClass("menu").addClass("menuselected");
    break;
    case 1:
      $("#all, #offline").removeClass("menuselected").addClass("menu"); 
      $("#online").removeClass("menu").addClass("menuselected");
    break;
    case 2:
      $("#offline, #online").removeClass("menuselected").addClass("menu"); 
      $("#all").removeClass("menu").addClass("menuselected");
    break;
  }
  tidyUp();
  outputUsers(users, url, urlSection, menu);
}

which calls:

function outputUsers(users, url, urlSection, selection) {

  users.forEach(function(user) {
    var dataArray = [];
    $.getJSON(url + urlSection[1] + user[1]).then(function(response) {

      if (response.stream) {
          var bgImage = response.stream.preview.medium;
          var game = response.stream.game;  
          dataArray.push(bgImage, game);
        //if online
        processOnlineUsers(user, url, urlSection, selection, dataArray);
      } else {
        dataArray.push(bgImage, "User currently Offline");
        processOfflineUsers(user, url, urlSection, selection, dataArray);
      }
    });
  });
}

I basically want 'user' available at the top level so I can use it to create an onclick event with an id that is made up like this $("#" + user[1] + "_playbutton")
Help!

Moisés Man
@moigithub
Mar 13 2018 22:01
ok.. so its ur own custom function u attached to res object... @tiagocorreiaalmeida
Adel
@AdelMahjoub
Mar 13 2018 22:04
@tiagocorreiaalmeida it could be something similar to this, used node cache to store the token with a lifetime, each time it needs the token it get it from node-cache, if it is expired it will be undefined, so it refresh the token and store it again. It always check the token before hitting the api.
https://github.com/AdelMahjoub/ng-nightlife-coordination-app/blob/master/services/yelp-access-token.service.js
https://github.com/AdelMahjoub/ng-nightlife-coordination-app/blob/master/services/yelp-search.service.js
@tiagocorreiaalmeida in other words it never hit the search api before checking the token from the cache
@tiagocorreiaalmeida that stdTTL: 15552000, is the token lifetime
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 22:08
@AdelMahjoub good one, thanks will implement for sure something similiar
CamperBot
@camperbot
Mar 13 2018 22:08
tiagocorreiaalmeida sends brownie points to @adelmahjoub :sparkles: :thumbsup: :sparkles:
:cookie: 674 | @adelmahjoub |http://www.freecodecamp.org/adelmahjoub
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 22:08
those were real brownies tough :D
Adel
@AdelMahjoub
Mar 13 2018 22:09
@tiagocorreiaalmeida where is my 9k brownies !! :laughing:
this bot is broken
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 22:13
how does the check period behaves here?
Adel
@AdelMahjoub
Mar 13 2018 22:13
@tiagocorreiaalmeida all handled by node-cache
@tiagocorreiaalmeida if the token is expired, reading the token from the cache return undefined,
@tiagocorreiaalmeida the api call is always a callback of the function that check/get/update the token
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 22:25
yeah @AdelMahjoub got the idea codefights just popped on the screen so I haven't done it yet but will now :D
Adel
@AdelMahjoub
Mar 13 2018 22:26
@tiagocorreiaalmeida you are really into codefights :smile:
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 22:26
just some times its a good way of relaxing and still coding :D
Tiago Correia
@tiagocorreiaalmeida
Mar 13 2018 23:46
image.png
function countAPI(calls) {
    let obj = {}
    for(let i = 0; i < calls.length; i++){
        let matches = calls[i].match(/\/(\w+)\/(\w+)\/(\w+)/);
        let project = matches[1],
            subProject = matches[2],
            method = matches[3];
        if(!obj[project]) obj[project] = {count: 0}

        if(!obj[project][subProject]) obj[project][subProject] = { count: 0 }

        if(!obj[project][subProject][method]) obj[project][subProject][method] = 0;

        obj[project].count++;
        obj[project][subProject].count++;
        obj[project][subProject][method]++;
    }

    let res = [];

    for(key in obj){
        let temp  = [];
        temp.push(`--${key} (${obj[key].count})`);
        for(key2 in obj[key]){
            let tempTwo = [];
            if(key2 !== "count"){
                for(key3 in obj[key][key2]){
                    let tempThree = [];
                    if(key3 === "count"){
                        tempThree.push(`----${key2} (${obj[key][key2].count})`);
                    }else{
                        tempThree.push(`------${key3} (${obj[key][key2][key3]})`);
                    }

                    tempTwo.push(...tempThree);
                }
            }
            temp.push(...tempTwo);
        }
        res.push(...temp);
    }
    return res;
}
can someone think of something simpler ? I dont even know..
:D
Jason Luboff
@JLuboff
Mar 13 2018 23:56
I don't have any time but that looks like my original solution to one of FCC algo challenges :joy: