These are chat archives for FreeCodeCamp/HelpJavaScript

2nd
Oct 2017
Stephen James
@sjames1958gm
Oct 02 2017 00:03
@carlosfrontend What I did was try to make change and if I got to the end and there was not enough change then I returned Insufficient funds.
Your code is not getting the change from each till
@tiagocorreiaalmeida You can return a promise from inside the .then of a promise to create a new one then chain .then
Jean-Paul Sauve
@jp-sauve
Oct 02 2017 01:37
I've got an issue with the Twitch project. https://github.com/jp-sauve/mister-twitch There are 2 branches to the project. The master branch, that has promises working, mostly there, but offline users are being added to the promise array. I created a PromiseRedo branch to change the order of things, but I'm not getting in to the Promise.all() section, and not getting errors. Can anyone take a look? The important code is in https://github.com/jp-sauve/mister-twitch/blob/PromiseRedo/src/composeTwitchStreamersList.js
Amit Patel
@AmitP88
Oct 02 2017 01:37
hey guys, I'm trying to get the second clicked on cell to determine whether or not it's adjacent to the first clicked on cell in the grid, but i'm having trouble figuring out what I need to do to make this work
https://codepen.io/AmitP88/pen/pWyaNY?editors=0010
Long Nguyen
@longnt80
Oct 02 2017 01:39
@AmitP88 can you assign each cell to a coordinate?
like a chess board
Amit Patel
@AmitP88
Oct 02 2017 01:40
@longnt80 I think each cell already has a coordinate though
@longnt80 like before, I wrote code that would print out the cells coordinates on any clicked on cell
It's going to be a 3 match game, so I don't know if I should hardcode each cells' coordinate
Long Nguyen
@longnt80
Oct 02 2017 01:42

@AmitP88 this is coordinate:

x: 7,
y: 1

?

Amit Patel
@AmitP88
Oct 02 2017 01:42
@longnt80 yeah
Long Nguyen
@longnt80
Oct 02 2017 01:43
hmm, why it is the same coordinate when I click any cell
Amit Patel
@AmitP88
Oct 02 2017 01:43
@longnt80 I'm not sure if I should hardcode the pixel coordinates, since I want this game to eventually port to mobile
???
hmmm, let me check
piteto
@piteto
Oct 02 2017 01:43
@jp-sauve $.getJSON is a promise already - so a function that returns your getJSON call is .thenable and can be included in your promise.all
I used promises as well: https://github.com/piteto/piteto.github.io/blob/master/twitch/js/index.js
Even though it doesn't use jQuery, the fetch() calls can be replaced with $.getJSON and used the same
Amit Patel
@AmitP88
Oct 02 2017 01:44
@longnt80 oh wait, because it's my array for the swap_container
@longnt80 I placed a length limit on it, so after the second clicked on cell, it won't log anymore cells to it
@longnt80 the array will be a mini container for swapping two user selected cells
piteto
@piteto
Oct 02 2017 01:46
you don't need to hard code any values @AmitP88. Use the top left and bottom right coordinates to determine the coordinates of every cell
top left = 0, 0, bottom right - 1200, 1200
8 squares per row would mean they're each 150 x 150
for example
Amit Patel
@AmitP88
Oct 02 2017 01:47
@piteto hmmm, well, I mean so far I've written code for determining what cell the user has clicked on (var clickedCell) and the left, top, right, and bottom adjacent cells to that user clicked cell. I was hoping I could use this info to write the swap functionality
piteto
@piteto
Oct 02 2017 01:47
as long as the click is less than 150 away from the last one (with the example numbers above), you're in an adjacent cell
150 I mean, it takes some math to figure out
Amit Patel
@AmitP88
Oct 02 2017 01:48
also, I eventually want to port this over to mobile, so I don't know if I should really assign pixel values like that as coordinates
piteto
@piteto
Oct 02 2017 01:49
x,y coordinates will be returned the same regardless of device size
you're not hard-coding anything, you're querying the x,y coordinates of the top, left and bottom, right, then doing the math
Amit Patel
@AmitP88
Oct 02 2017 01:50
hmmm, wouldn't that kinda break the DRY rule though?
piteto
@piteto
Oct 02 2017 01:50
How so?
Amit Patel
@AmitP88
Oct 02 2017 01:50
well, because it would be repeating code by writing the x,y for all 64 cells
piteto
@piteto
Oct 02 2017 01:51
no, it would be one algorithm that determines the x,y for all cells
Amit Patel
@AmitP88
Oct 02 2017 01:52
I thought I was doing that already lol
      var rect = canvas.getBoundingClientRect();

      // User clicked cell
      var x = Math.floor(event.clientX - rect.left);
      var y = Math.floor(event.clientY - rect.top);
      var cellW = Math.floor(x/cell.width);
      var cellH = Math.floor(y/cell.height);

      var clickedCell = {
        x : cellW,
        y : cellH,
        image : grid[cellW + gridSize * cellH].image 
      };

    swap_container.push(clickedCell);

    if (swap_container.length > 2) {
      swap_container.length = 2;
    }    
    console.log(swap_container);
    console.log(swap_container.length);












          /* Cells that are adjacent to the user clicked cell */
      // left adjacent cell of user clicked cell
      var x_left = Math.floor((event.clientX - cell.width) - rect.left);
      var cellW_left = Math.floor(x_left/cell.width);

      var adjacentCell_left = {
          x : cellW_left,
          y : clickedCell.y,
          image : grid[cellW_left + gridSize * clickedCell.y].image
      }

      // right adjacent cell of user clicked cell
      var x_right = Math.floor((event.clientX + cell.width) - rect.left);
      var cellW_right = Math.floor(x_right/cell.width);

      var adjacentCell_right = {
        x : cellW_right,
        y : clickedCell.y,
        image : grid[cellW_right + gridSize * clickedCell.y].image
      }

      // top adjacent cell of user clicked cell
      var y_top = Math.floor((event.clientY - cell.width) - rect.top);
      var cellH_top = Math.floor(y_top/cell.width);

      var adjacentCell_top = {
        x : clickedCell.x,
        y : cellH_top,
        image : grid[clickedCell.x + gridSize * cellH_top].image
      }

      // bottom adjacent cell of user clicked cell
      var y_bottom = Math.floor((event.clientY + cell.width) - rect.top);
      var cellH_bottom = Math.floor(y_bottom/cell.width);

      var adjacentCell_bottom = {
        x : clickedCell.x,
        y : cellH_bottom,
        image : grid[clickedCell.x + gridSize * cellH_bottom].image
      }
piteto
@piteto
Oct 02 2017 01:56
That's a lot of code to figure out the coordinates for all the cells
I was thinking you'd have to a top left and a bottom right, then have an array of cells + coordinates
Amit Patel
@AmitP88
Oct 02 2017 01:57
well I mean, it only really calculates the position of the clicked cell and the immediate surrounding cells of that clicked cell
piteto
@piteto
Oct 02 2017 01:57
I guess you're creating separate objects for each adjacent cell
Amit Patel
@AmitP88
Oct 02 2017 01:57
yup
piteto
@piteto
Oct 02 2017 01:58
There may be a mathematical algorithm already written that determines this for you, but I think it needs to be based on how far away the second click is from the first
or, ideally, get a coordinate like column/row
Amit Patel
@AmitP88
Oct 02 2017 02:00
hmmm, there might be. I might have to play around with the cell.width and cell.heights to calculate them though
piteto
@piteto
Oct 02 2017 02:01
cell b3 is adjacent to b2, b4, a2, a3, a4, c2, c3, and c4
Amit Patel
@AmitP88
Oct 02 2017 02:02
ah I see
I figured the way I was trying to do it would be a shorter way around, but looks like that won't be possible
Amit Patel
@AmitP88
Oct 02 2017 02:03
ah ok, this looks good. I'll read into it :)
piteto
@piteto
Oct 02 2017 02:03
Good luck :)
Amit Patel
@AmitP88
Oct 02 2017 02:03
@piteto thank you :)
CamperBot
@camperbot
Oct 02 2017 02:03
amitp88 sends brownie points to @piteto :sparkles: :thumbsup: :sparkles:
:cookie: 178 | @piteto |http://www.freecodecamp.com/piteto
Jean-Paul Sauve
@jp-sauve
Oct 02 2017 02:04
@piteto I haven't fixed it yet. Maybe tomorrow. Thanks for the advice, and for taking a look.
CamperBot
@camperbot
Oct 02 2017 02:04
jp-sauve sends brownie points to @piteto :sparkles: :thumbsup: :sparkles:
:cookie: 179 | @piteto |http://www.freecodecamp.com/piteto
piteto
@piteto
Oct 02 2017 02:04
Promises are tough to grasp at first, good luck @jp-sauve
Bradley Sands
@sandsbe
Oct 02 2017 02:57
Node install question. I downloaded from the https://nodejs.org/en/download/ for Windows.
It's installed in Program Files. I want to start a project in a different folder.
Keep getting "'npm' is not recognized as an internal or external command,
operable program or batch file."
Seems to be a major logic step either I'm missing or is just understood by everyone else
SORRY! Just realized I'm in the wrong room.
Claudio Restifo
@Marmiz
Oct 02 2017 03:01
@sandsbe can you try a node -v and npm -v to see if they are correctly installed?
Bradley Sands
@sandsbe
Oct 02 2017 03:01
Yup. I got v6.11.3 and 3.10.10
```jsC:\Program Files\nodejs>node -v
v6.11.3
C:\Program Files\nodejs>npm -v
3.10.10
C:\Program Files\nodejs>node -v
v6.11.3

C:\Program Files\nodejs>npm -v
3.10.10
Claudio Restifo
@Marmiz
Oct 02 2017 03:02
So you are in a fresh directory, can you nom init?
Bradley Sands
@sandsbe
Oct 02 2017 03:03
C:\Users\Brad\hello-node trying to run npm init
Claudio Restifo
@Marmiz
Oct 02 2017 03:03
btw you probably have to restart windows after the node install
Bradley Sands
@sandsbe
Oct 02 2017 03:03
HA!
If it's that simple I'm throwing this laptop out the window
Claudio Restifo
@Marmiz
Oct 02 2017 03:04
windows ;)
Bradley Sands
@sandsbe
Oct 02 2017 03:04
thanks for your help @Marmiz . I'll be right back!
CamperBot
@camperbot
Oct 02 2017 03:04
sandsbe sends brownie points to @marmiz :sparkles: :thumbsup: :sparkles:
:star2: 1051 | @marmiz |http://www.freecodecamp.com/marmiz
Claudio Restifo
@Marmiz
Oct 02 2017 03:04
let me know :)
Bradley Sands
@sandsbe
Oct 02 2017 03:08
IT WORKED!
Leave it to Microsoft to omit that major step in its own program. https://courses.edx.org/courses/course-v1:Microsoft+DEV280x+2T2017/course/
Claudio Restifo
@Marmiz
Oct 02 2017 03:10

¯\(ツ)

at least it worked

Bradley Sands
@sandsbe
Oct 02 2017 03:15
Anyone use Microsoft Visual Studio Code? I've used Atom/Brackets but this doesn't seem too bad.
Claudio Restifo
@Marmiz
Oct 02 2017 03:16
We recently started naming it as "suggested" at work for certain projects.
I yet have to try it seriously, but for now has replaced Atom in the rare instances that I needed it
Has a huge trending as well
Bradley Sands
@sandsbe
Oct 02 2017 03:18
Nice. I see some value is possibly hitching my learning wagon to a big player like Microsoft. They feel so inadequate in the developer/startup space that they provide a ton of free stuff.
Gersho
@Gersho
Oct 02 2017 03:20
i have to admit i was quite surprise when i learned VSC was that popular (even among linux users !)
Bradley Sands
@sandsbe
Oct 02 2017 03:25
C:\Users\Brad\hello-node>node server.js
Listening on port 3000
New request to: /
New request to: /robots.txt
New request to: /favicon.ico
Any idea how to close/stop the server from here? It won't let me type anything.
Claudio Restifo
@Marmiz
Oct 02 2017 03:25
CTRL+C
or cmd+c on Mac
Bradley Sands
@sandsbe
Oct 02 2017 03:26
^c worked, I think. Ctrl+C may have also worked but I know it allowed me to copy for the paste into the chat.
Thanks again @Marmiz
CamperBot
@camperbot
Oct 02 2017 03:26
sandsbe sends brownie points to @marmiz :sparkles: :thumbsup: :sparkles:
api offline
Bradley Sands
@sandsbe
Oct 02 2017 03:29
Question if anyone out there is bored. In the package.json, what is the entry point field? At this point the tutorial is telling me to use server.js, which makes sense because that's what I'm writing. But default is index.js. Is this similar to index.html? i.e., the "Home"?
Claudio Restifo
@Marmiz
Oct 02 2017 03:34
@sandsbe can be any file you want.
If you are writing node it's general the entry point of your server.
(call it whatever: server.js - index.js - myawesomeserver.js ...)
It's basically where node will start looking into
Bradley Sands
@sandsbe
Oct 02 2017 03:35
:+1:
Claudio Restifo
@Marmiz
Oct 02 2017 03:36
nvm I was thinking of node, in npm is the "root" of your bundle.
So that once expiorted, a user can import * from 'yourmainfile and import all bundle
Bradley Sands
@sandsbe
Oct 02 2017 03:43
:hamburger:
Adam Faraj
@adamfaraj
Oct 02 2017 04:01
how do i wrap my div in an anchor tag in JS?
var newDiv = document.createElement("div"); //setting up a div to inject results into DOM
                newDiv.id = "divResults";
                newDiv.class = "divResults";

                var a = document.createElement('a');
                a.href = 'https://en.wikipedia.org/wiki/?curid=' + item[1].pageid;
                a.target = "_blank";
                a.class = "resultsLink";
                // var aText = document.createTextNode("Click here for article");
                // a.appendChild(aText);

                var h1 = document.createElement("h1");
                var titleText = document.createTextNode(item[1].title);
                h1.appendChild(titleText);
                var snippetText = document.createTextNode(item[1].extract);

                //populating div with data
                h1.appendChild(a);
                newDiv.appendChild(h1);
                newDiv.appendChild(snippetText);
                newDiv.appendChild(a);
                var finalDiv = $(".divResults").wrap($('.resultsLink'));
                finalDiv.class = "finalDiv";


                document.body.appendChild($(".divResults").wrap($('.resultsLink')));
heroiczero
@heroiczero
Oct 02 2017 04:05
are you trying to do it without Jquery or with?
Adam Faraj
@adamfaraj
Oct 02 2017 04:06
doesn't matter
just trying to get it to work. haha
heroiczero
@heroiczero
Oct 02 2017 04:13
personally i would use .html() for Jquery to create a markup or you could a.appendChild(div) some thing like that too
Adam Faraj
@adamfaraj
Oct 02 2017 04:15
@heroiczero a.appendChild(div) didn't work
i'm just trying to get the whole div to become a link to it's wikipedia article
heroiczero
@heroiczero
Oct 02 2017 04:18
document.getElementById("link").appendChild("div"); something like this may work
Gersho
@Gersho
Oct 02 2017 04:19
.html("<a><div></div></a>") ?
Adam Faraj
@adamfaraj
Oct 02 2017 04:23
@heroiczero
 newDiv.appendChild(h1);
                newDiv.appendChild(snippetText);
                a.appendChild(newDiv);
                // var finalDiv = $(".divResults").wrap($('.resultsLink'));
                // finalDiv.class = "finalDiv";


                document.body.appendChild(a);
                dom.searchText.value = ''; //resetting search input
this worked
putting a.appendChild(newDiv) after
my order was messed up
thanks @heroiczero !
CamperBot
@camperbot
Oct 02 2017 04:23
adamfaraj sends brownie points to @heroiczero :sparkles: :thumbsup: :sparkles:
:star2: 1802 | @heroiczero |http://www.freecodecamp.com/heroiczero
yofri
@yofriadi
Oct 02 2017 06:11
guys how to sort this
console.log(mostFrequentItem(['asus', 'asus', 'samsung', 'iphone','iphone', 'asus','asus']));
// samsung(1), iphone(2) , asus(4)

console.log(mostFrequentItem([9,'b','b','c',9,9,'b',9, 2,2]));
// c(1) , 2(2) ,b(3) ,9(4)
Markus Kiili
@Masd925
Oct 02 2017 06:12
@Yofri For sorting an array, you can use .sort() method and suitable callback function that defines the sorting order.
Maybe something else is better than sort here.
yofri
@yofriadi
Oct 02 2017 06:14

here my answer

function mostFrequentItem(arr) {
  arr = arr.sort();
  const result = [];

  const filtered = arr.filter((val, pos) => arr.indexOf(val) === pos);

  for (let i = 0; i < filtered.length; i++) {
    let counter = 0;

    for (let j = 0; j < arr.length; j++) {
      if (filtered[i] === arr[j]) {
        counter++;
      }
    }

    result.push(`${filtered[i]}(${counter})`)
  }

  return result;
}

but shows asus(4), iphone(2), samsung(1) and 2(2), 9(4), b(3), c(1)
I dont know how to sort this

Fabien SHAN
@X140hu4
Oct 02 2017 06:34
reverse the result?
ah hmmm
Henry
@GitHub-Henry
Oct 02 2017 07:10
Using ES6, consider this
Markus Kiili
@Masd925
Oct 02 2017 07:19
@Yofri Does this work as expected:
function mostFrequentItem(arr) {
  var obj = {};
  arr.forEach(function(elem){
    obj[elem] = obj.hasOwnProperty(elem) ? obj[elem]+1 : 1;
  });
  return Object.keys(obj).sort(function(a,b){
    return obj[a]-obj[b];
  }).map(function(elem){
    return elem + "(" + String(obj[elem]) + ")";
  });
}
yofri
@yofriadi
Oct 02 2017 07:20
@Masd925 thanks man, i will learn the code
CamperBot
@camperbot
Oct 02 2017 07:20
yofri sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4516 | @masd925 |http://www.freecodecamp.com/masd925
Blauelf
@Blauelf
Oct 02 2017 07:26
@Masd925 Might be interesting when your array contains "__proto__"
Markus Kiili
@Masd925
Oct 02 2017 07:32
@Blauelf Would this avoid it:
Blauelf
@Blauelf
Oct 02 2017 07:32
Interesting. Assigning a non-object to obj.__proto__ doesn't seem to break anything.
Markus Kiili
@Masd925
Oct 02 2017 07:32
function mostFrequentItem(arr) {
  var obj = Object.create(null);
  arr.forEach(function(elem){
    obj[elem] = obj[elem] ? obj[elem]+1 : 1;
  });
  return Object.keys(obj).sort(function(a,b){
    return obj[a]-obj[b];
  }).map(function(elem){
    return elem + "(" + String(obj[elem]) + ")";
  });
}
Blauelf
@Blauelf
Oct 02 2017 07:33
@Masd925 __proto__ property is not enumerable, so it won't show up. But I found a better one to actually break the first version: "hasOwnProperty" :)
Markus Kiili
@Masd925
Oct 02 2017 07:34
@Blauelf How does hasOwnProperty differ from __proto__?
Both are inherited non-enumerable property keys.
Blauelf
@Blauelf
Oct 02 2017 07:41
hasOwnProperty is the one you actively use in the first version.
Markus Kiili
@Masd925
Oct 02 2017 07:44
@Blauelf Yeah. Proto and hawOwnProperty also seem to differ on the writability aspect.
Blauelf
@Blauelf
Oct 02 2017 07:52
I really like that we now have Map and no longer have to abuse objects.
Markus Kiili
@Masd925
Oct 02 2017 07:54
@Blauelf Yes, this solution was a nice reminder. Thanks.
CamperBot
@camperbot
Oct 02 2017 07:54
masd925 sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 4619 | @blauelf |http://www.freecodecamp.com/blauelf
Blauelf
@Blauelf
Oct 02 2017 07:55
Also, object keys can only be strings. Map keys can be anything.
Interesting. Even NaN is a valid key. But -0 and +0 are treated as equal it seems.
That moment when you divide 1/0 to check for the sign of the zero...
Kelechi Chinaka
@ke1echi
Oct 02 2017 08:17
i did a kata and saw your binary solution...it was cool @Blauelf
whats the best way to learn algorithms @Blauelf
Blauelf
@Blauelf
Oct 02 2017 08:18
Binary solution?
what do u think is a good way to learn algorithms? @Blauelf
Blauelf
@Blauelf
Oct 02 2017 08:27

Ah, that binary search.

Good question. I mostly learnt them as I needed (or thought I might). Also, CS50x might be some address to consider for some basic algorithms.

Kelechi Chinaka
@ke1echi
Oct 02 2017 08:28
thanks @Blauelf :+1:
CamperBot
@camperbot
Oct 02 2017 08:28
kelechy sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 4620 | @blauelf |http://www.freecodecamp.com/blauelf
Blauelf
@Blauelf
Oct 02 2017 08:29
And based on the time I learnt programming, most of my learning was somewhat game-mechanics-related.
Kelechi Chinaka
@ke1echi
Oct 02 2017 08:30
i see... because that binary logic was cool
Blauelf
@Blauelf
Oct 02 2017 08:33
Binary search. Divide and conquer.
Jen
@jenniredfield
Oct 02 2017 08:33
Could anyone help me with my twitch app -_-
got all data I need in 'obj' but a for key in obj is not working to display it?
am I having a scope problem or ...?
Claudio Restifo
@Marmiz
Oct 02 2017 08:49
@jenniredfield is your goal having an object with all the data in?
because so far you override it with every map iteration
Jen
@jenniredfield
Oct 02 2017 08:57
ahhh ok
but if I console log out I can see my data there?
tahashin
@tahashinegp
Oct 02 2017 09:01
Build a Random Quote Machine. One question? for showing quote i have to crea json file? and some quote there?
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 09:01
there's some api's that do that part of the job for you
tahashin
@tahashinegp
Oct 02 2017 09:02
or there is any kind of open api for that? can anyone help me
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 09:02
I think they give you a example api in the projecti nfo
tahashin
@tahashinegp
Oct 02 2017 09:03
in code pen? right
lets see
i have to see source code than

Objective: Build a CodePen.io app that is functionally similar to this: https://codepen.io/FreeCodeCamp/full/ONjoLe/.

Fulfill the below user stories. Use whichever libraries or APIs you need. Give it your own personal style.

User Story: I can click a button to show me a new random quote.

User Story: I can press a button to tweet out a quote.

Remember to use Read-Search-Ask if you get stuck.

When you are finished, click the "I've completed this challenge" button and include a link to your CodePen.

You can get feedback on your project by sharing it with your friends on Facebook.

Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 09:04
@tahashinegp sec will give you the api I used
@tahashinegp
tahashin
@tahashinegp
Oct 02 2017 09:08
@tiagocorreiaalmeida thanks a lot
CamperBot
@camperbot
Oct 02 2017 09:08
tahashinegp sends brownie points to @tiagocorreiaalmeida :sparkles: :thumbsup: :sparkles:
:cookie: 374 | @tiagocorreiaalmeida |http://www.freecodecamp.com/tiagocorreiaalmeida
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 09:10
anytime
Ghost
@ghost~59cdefc7d73408ce4f77dab0
Oct 02 2017 14:42
Can anyone explain how this typewriter thing actually works? I'm a rookie at JS right now.-
https://codepen.io/geoffgraham/pen/jrWwWM
Stephen James
@sjames1958gm
Oct 02 2017 14:46
@parthprakash1 The following creates animation frames, transition from zero width to full width.
Then the animation will cause it to appear to type while it is just expanding the width of the h1.
@keyframes typing {
  from { width: 0 }
  to { width: 100% }
}
@parthprakash1 this references the typing keyframes above (BTW, there is no js involved here)
  animation: 
    typing 3.5s steps(30, end),
    blink-caret .5s step-end infinite;
Ghost
@ghost~59cdefc7d73408ce4f77dab0
Oct 02 2017 15:01
Righttt! Thanks @sjames1958gm
CamperBot
@camperbot
Oct 02 2017 15:01
parthprakash1 sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8503 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Razvan Jackson
@RazvanJackson
Oct 02 2017 15:07
Who knows c++
Ronique Ricketts
@RoniqueRicketts
Oct 02 2017 15:07
if C was 0 then C++ is now 1 :trollface:
Diego Mayer
@Chrono79
Oct 02 2017 15:12
@RoniqueRicketts previous value of c+1 is more general answer :trollface:
@RazvanJackson not me
Ronique Ricketts
@RoniqueRicketts
Oct 02 2017 15:12
@Chrono79 aaaaah hahahaha
Jason Luboff
@JLuboff
Oct 02 2017 15:13
:wave:
Diego Mayer
@Chrono79
Oct 02 2017 15:13
:wave:
Ronique Ricketts
@RoniqueRicketts
Oct 02 2017 15:13
:wave:
Jason Luboff
@JLuboff
Oct 02 2017 15:14
Whats happening?
Diego Mayer
@Chrono79
Oct 02 2017 15:16
Day 3 of pharyngitis, I was dying in the previous days, now I'm better
Jason Luboff
@JLuboff
Oct 02 2017 15:17
@Chrono79 Looks like strep throat?
WAINGOR
@WAINGOR
Oct 02 2017 15:18

Hi all, I have a question about the code below:
I am looking for the most clean/succinct way to perform this action:

var cid = [1,2,3,4,5];
  var bigToSmallOld = [];
  for (var l=0; l<cid.length; l++) {
     bigToSmallOld.unshift(cid[l]);
  }

I tried reduce, but the function within reduce performs an unshift, which returns a number... therefore after 1 iteration it breaks... Any suggestions?

var cid = [1,2,3,4,5];
var bigToSmallOld = cid.reduce((accu,cur,i)=>accu.unshift(cur),[]);
Diego Mayer
@Chrono79
Oct 02 2017 15:18
yes I couldn't even swallow my own saliva for the pain @JLuboff
Jason Luboff
@JLuboff
Oct 02 2017 15:18
@Chrono79 Oh man...that sounds horrible
Diego Mayer
@Chrono79
Oct 02 2017 15:18
and they told me to drink a lot of water :confused:
Jason Luboff
@JLuboff
Oct 02 2017 15:19
@Chrono79 Does a straw help or make it worse?
Blauelf
@Blauelf
Oct 02 2017 15:19
@WAINGOR Why would you do it that way? And why do you want to do that in the first place?
Diego Mayer
@Chrono79
Oct 02 2017 15:19
@JLuboff no help, at the end, you have to swallow to drink or eat
Jason Luboff
@JLuboff
Oct 02 2017 15:20
Ugh. Sorry to hear that, hope you continue to heal
WAINGOR
@WAINGOR
Oct 02 2017 15:20
@Blauelf because I need to turn an array around, and because I want to write it down using the minimum amount of characters
Diego Mayer
@Chrono79
Oct 02 2017 15:20
thanks @JLuboff
CamperBot
@camperbot
Oct 02 2017 15:20
chrono79 sends brownie points to @jluboff :sparkles: :thumbsup: :sparkles:
:star2: 2211 | @jluboff |http://www.freecodecamp.com/jluboff
Diego Mayer
@Chrono79
Oct 02 2017 15:21
@WAINGOR is using reverse() forbidden?
Blauelf
@Blauelf
Oct 02 2017 15:21
@WAINGOR What do you mean with "turn an array around"? Like var bigToSmallOld = cid.slice().reverse();? (.slice() just for not altering cid)
With Python, it would be cid[::-1] :D
WAINGOR
@WAINGOR
Oct 02 2017 15:24
@Blauelf looool I never knew about reverse! talking about succinct. OK so anytime I call slice without passing it arguments it will just return the entire array?
Jason Luboff
@JLuboff
Oct 02 2017 15:25
You never knew about reverse?? Its one of the early on FCC basic javascript challenges
Blauelf
@Blauelf
Oct 02 2017 15:25
@WAINGOR How did you solve reverse-a-string then? Manually iterating the string?
@WAINGOR slice without arguments creates a shallow copy of an array (as first argument defaults to 0 and second argument defaults to array length)
WAINGOR
@WAINGOR
Oct 02 2017 15:26
@korzo my console tells a different story:
var cid = [1,2,3,4,5];
undefined
var X = cid.slice();
undefined
X
(5) [1, 2, 3, 4, 5]
Blauelf
@Blauelf
Oct 02 2017 15:27
What's the different story then?
korzo
@korzo
Oct 02 2017 15:27
@WAINGOR Sorry, I misread your question. It was for str.split(), not slice
Blauelf
@Blauelf
Oct 02 2017 15:27
Ah, that one.
WAINGOR
@WAINGOR
Oct 02 2017 15:27
@JLuboff I didnt knew about the method called reverse. If you read my post U would see that my code would pass that test called reverse
Blauelf
@Blauelf
Oct 02 2017 15:28
@WAINGOR Beware that reverse returns the reversed array, but that's the same array it was called on (it reverses in-place, so if you want to keep the original array, you have to create a copy first)
Diego Mayer
@Chrono79
Oct 02 2017 15:30
@WAINGOR take a look at MDN docs once in a while, it'll help you discover things that are already made so you don't have to reinvent the wheel ;)
Also you'll see the things you have to keep in mind like Blauelf told above
Kelechi Chinaka
@ke1echi
Oct 02 2017 15:30
guys can you make sense out of this kata...the wordings are bad
:wave: guys
Diego Mayer
@Chrono79
Oct 02 2017 15:31
@kelechy yes
you have to return the max length difference between the strings in both arrays
in the test case, 13 is the length of cccooommaaqqoxii (16) minus oox (3)
Amit Patel
@AmitP88
Oct 02 2017 15:32
hey guys, I'm redoing my project and I'm already running into problems. when I try to run my code, it says that I have an infinite loop. How do I fix my for loop to resolve this?
https://codepen.io/AmitP88/pen/pWyaNY?editors=0010
WAINGOR
@WAINGOR
Oct 02 2017 15:32
thanks @Blauelf !
CamperBot
@camperbot
Oct 02 2017 15:32
waingor sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 4621 | @blauelf |http://www.freecodecamp.com/blauelf
Diego Mayer
@Chrono79
Oct 02 2017 15:35
@kelechy did that help clarifying?
Kelechi Chinaka
@ke1echi
Oct 02 2017 15:35
oh... @Chrono79 ... some descriptions can make u look stu* ...thanks man
CamperBot
@camperbot
Oct 02 2017 15:35
kelechy sends brownie points to @chrono79 :sparkles: :thumbsup: :sparkles:
:star2: 4563 | @chrono79 |http://www.freecodecamp.com/chrono79
Diego Mayer
@Chrono79
Oct 02 2017 15:35
no problem
Kelechi Chinaka
@ke1echi
Oct 02 2017 15:37
i hope u heal fast too @Chrono79
Stephen James
@sjames1958gm
Oct 02 2017 15:44
@RazvanJackson If you still need help - I know C++ -
Diego Mayer
@Chrono79
Oct 02 2017 15:45
:+1: me too, more than anyone else ;)
Ronique Ricketts
@RoniqueRicketts
Oct 02 2017 15:48
@Chrono79 stop lying.
Stephen James
@sjames1958gm
Oct 02 2017 15:48
@AmitP88 array.push(populator(i,j)); don't push values on to the same array you are looping on.
Perhaps a different array is what you meant
Blauelf
@Blauelf
Oct 02 2017 15:58

Reminds me of my (probably not very efficient) solution

function steamrollArray(arr) {
  arr = arr.slice();
  var i = 0;
  while (i < arr.length) {
    if (Array.isArray(arr[i])) {
      arr.splice(i, 1, ...arr[i]);
    } else {
      i++;
    }
  }
  return arr;
}

I tried hard to not mess up with indices. One of my ugliest solutions to this one :D

Amit Patel
@AmitP88
Oct 02 2017 16:01
@sjames1958gm hmmm, I tried this way (based on my console.log) and it still didn't work.
https://codepen.io/AmitP88/pen/pWyaNY?editors=0010
Blauelf
@Blauelf
Oct 02 2017 16:03
array[i][j] is not an array, so has no push method.
That's why
TypeError: array[i][j].push is not a function
@AmitP88 You check the browser's console log (in the dev tools, F12 on most browsers), not just the codepen console log, right?
Amit Patel
@AmitP88
Oct 02 2017 16:08
yeah, i checked it
how do I use the populator function to generate a random image in each index of the 2d array?
I can't seem to figure it out
Blauelf
@Blauelf
Oct 02 2017 16:12
You mean something like array[i][j] = populator(100*i, 100*j);? (not sure that's what you want, but it creates some graphics)
Amit Patel
@AmitP88
Oct 02 2017 16:12
basically each index in the 2d array should have it's own randomly generated image using the populator function
ah ok, I guess I was trying to use the push method inappropriately
Kelechi Chinaka
@ke1echi
Oct 02 2017 16:15
i still dont get it, failing all random test @Chrono79
pls i need more explanation @Chrono79
Blauelf
@Blauelf
Oct 02 2017 16:17
Still the longest minus shortest?
Kelechi Chinaka
@ke1echi
Oct 02 2017 16:18
yes pls @Blauelf
the wordings are so unclear
Blauelf
@Blauelf
Oct 02 2017 16:19
I calculated length for both arrays' strings, took minimum and maximum of each, and took the maximum of the pairwise difference (maximum of max1-min2 and max2-min1)
You have to find the maximum difference of the word lengths with one string picked from the first and one from the second array. That could be longest of first and shortest of second or the other way around.
Kelechi Chinaka
@ke1echi
Oct 02 2017 16:30
pls show me an example of what you mean by pairwise @Blauelf
its getting me confused
looks like description says Math.abs(min of 1st arr - max of 2nd arr)
Manish Giri
@Manish-Giri
Oct 02 2017 16:37
@kelechy for each word from one array, calculate it's length difference for each word in the second array
Blauelf
@Blauelf
Oct 02 2017 16:38
@kelechy min of first and max of second or max of first and min of second, whichever is the bigger difference.
@Manish-Giri Sounds like you're suggesting a O(mn)\mathcal{O}(m\cdot n) solution while O(m+n)\mathcal{O}(m+n) would work as well (by using only the minimum/maximum of the individual arrays).
Don't know whether it matters at all for this one.
Manish Giri
@Manish-Giri
Oct 02 2017 16:40
@Blauelf I tried that, didn't work..
60 passed, 40 failed
Kelechi Chinaka
@ke1echi
Oct 02 2017 16:42
thanks guys @Chrono79 @Blauelf @Manish-Giri
CamperBot
@camperbot
Oct 02 2017 16:42
kelechy sends brownie points to @chrono79 and @blauelf and @manish-giri :sparkles: :thumbsup: :sparkles:
:star2: 6609 | @manish-giri |http://www.freecodecamp.com/manish-giri
Jason Luboff
@JLuboff
Oct 02 2017 16:43
Passed with an ugly solution :P
Diego Mayer
@Chrono79
Oct 02 2017 16:43
@Manish-Giri what @Blauelf told worked for me (that's what I did)
Blauelf
@Blauelf
Oct 02 2017 16:43
@Manish-Giri What did not work? Minimum and maximum of both arrays?
function mxdiflg(a1, a2) {
    let l1 = a1.map(word=>word.length);
    let l2 = a2.map(word=>word.length);
    return a1.length && a2.length ? Math.max(Math.max(...l1) - Math.min(...l2), Math.max(...l2) - Math.min(...l1)) : -1;
}
Kelechi Chinaka
@ke1echi
Oct 02 2017 16:43
understanding the description was more pain than the code :smile:
CamperBot
@camperbot
Oct 02 2017 16:43
:star2: 4622 | @blauelf |http://www.freecodecamp.com/blauelf
Kelechi Chinaka
@ke1echi
Oct 02 2017 16:43
mine is uglier @JLuboff :smile:
CamperBot
@camperbot
Oct 02 2017 16:43
api offline
Manish Giri
@Manish-Giri
Oct 02 2017 16:44
function mxdiflg(a1, a2) {
const d1 = Math.abs(Math.min(...a1.map(e => e.length)) - Math.max(...a2.map(e => e.length)));
const d2 = Math.abs(Math.max(...a1.map(e => e.length)) - Math.min(...a2.map(e => e.length)));
return !a1.length || !a2.length ? -1 : d1 > d2 ? d1 : d2;
}
(this worked)
@Blauelf
Jason Luboff
@JLuboff
Oct 02 2017 16:44
function mxdiflg(a1, a2) {
let a1Sort = a1.sort((a,b) => a.length < b.length);
let a2Sort = a2.sort((a,b) => a.length < b.length);

return a1.length === 0 || a2.length === 0 ?-1:(a1Sort[0].length - a2Sort[a2.length - 1].length) > (a2Sort[0].length - a1Sort[a1.length - 1].length) ? a1Sort[0].length - a2Sort[a2.length - 1].length : a2Sort[0].length - a1Sort[a1.length - 1].length;
    }
Blauelf
@Blauelf
Oct 02 2017 16:46
@Manish-Giri That's not comparing all pairs, you're using the O(m+n)\mathcal{O}(m+n) approach.
@JLuboff You really know how much I like sort for finding minimum/maximum :D
Jason Luboff
@JLuboff
Oct 02 2017 16:49
@Blauelf You know...I seem to recall that you don't care for sort
In fact... @Masd925 may have made a joke or two about it
Diego Mayer
@Chrono79
Oct 02 2017 16:56
function mxdiflg(a1, a2) {
    if (a1.length === 0 || a2.length === 0) return -1;
    a1 = a1.map(a => a.length);
    a2 = a2.map(a => a.length);
    return Math.max(Math.max(...a1)-Math.min(...a2), Math.max(...a2)-Math.min(...a1));
}
@Manish-Giri you wouldn't need the Math.abs if you do max - min
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:01
hi everyone, I a problem with showing the e.target.name onClick. I get undefined when i click on in element that is bound to an onclick function and has a name attribute . any guesses?
class EventVoteDisc extends React.Component {
  constructor(props){
    super(props);
    this.onClick = this.onClick.bind(this);
  }
  onClick(e){
    e.preventDefault();

    var el= e.target;
    console.log("target" + el);
    console.log("option" + e.target.name);
  }
  render(){
    var options = this.props.options.map((option, index )=>
      <div key={index} className="row" >
        <button type="button" className = "btn btn-default custom-button">
        <h3 className="col-xs-6">{option[0]}:</h3>
        <h3 className="col-xs-6">{option[1]}</h3>
        </button>

      </div>);
    return (

      <div onClick={this.onClick} name = "hamsi">
        {options}
      </div>
    );
  }
}
Stephen James
@sjames1958gm
Oct 02 2017 17:03
@AmitP88 If you didn't want to prefill that array you had you could have done:
  let width = 8;
  let height = 8;
  let array = [];
  for (var i = 0; i < height; i++) {
    let a = [];
    for (var j = 0; j < width; j++) {
      a.push(populator(100*i, 100*j));
    }
    array.push(a);
  }
Amit Patel
@AmitP88
Oct 02 2017 17:04
@sjames1958gm that code seems better. :)
Stephen James
@sjames1958gm
Oct 02 2017 17:04
@ahmadabdolsaheb likely name is not a standard attribute of a div, you would have to do
e.target.getAttribute("name");
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:04
Can anyone tell me why this code doesn't work? It's the "Sum All Primes" challenge
//noprotect
function test_prime(n) {
if (n===1)
  {
    return false;
  }
  else if(n === 2)
  {
    return true;
  }else
{
    for(var x = 2; x < n; x++)
    {
      if(n % x === 0)
      {
        return false;
      }
    }
    return true;  
  }
}

function sumPrimes(num) {
 var listOfNum = [];
 var listOfPrimes = [];
  for (var i = 2; i < num; i++) {
    listOfNum.push(i);
  }
for (var j =0; j < listOfNum.length; j++) {
  if (test_prime(j) == true) {
    listOfPrimes.push(j);
  }
}

  var reducedList = listOfPrimes.reduce(function(a,b) {
    return a + b;
  });
  return reducedList;
}



sumPrimes(73156);
Amit Patel
@AmitP88
Oct 02 2017 17:05
@sjames1958gm oh wait, actually, before I started over, my code was similar to that
Diego Mayer
@Chrono79
Oct 02 2017 17:05
@EricHasegawa should num be included or not?
Amit Patel
@AmitP88
Oct 02 2017 17:06
@sjames1958gm I'm making a 3 match game, and my old code was overly complicated to the point where I was having trouble (still am) creating the swap functionality between two adjacent cells
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:06
@Chrono79 What do you mean?
Stephen James
@sjames1958gm
Oct 02 2017 17:06
@EricHasegawa i < num this will not put num into your array
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:08
@sjames1958gm if I use i < num + 1 the problem still persists
Amit Patel
@AmitP88
Oct 02 2017 17:08
@sjames1958gm
window.onload = function() {
  const gridSize = 8; // setting the amount of rows and columns the grid will have (in this case it will be an 8 x 8 grid)
  var canvas = document.getElementById('canvas'); // obtain canvas element from DOM
  var context = canvas.getContext('2d'); // set canvas' context
  var cell; // will serve as a new cell object
  var grid; // will be a container for the generated cell objects
  var tileImgs; // will be an array that will store all the tile images to be randomly generated inside cell objects
  var mouse; // will hold the current mouse (x,y) position
  var xPos = 0; // will hold cell's x position in grid. Default x position set to 0
  var yPos = 0; // will hold cell's y position in grid Default y position set to 0

  // function that will setup the game and game objects
  function setCanvas() {
    grid = [];  // set grid to an array object
    grid.width = canvas.width; // set grid width
    grid.height = canvas.height; // set grid height

    // Creates column lines for grid (only used as a guide to visualize the grid)
    for (let x=100; x < grid.width; x=x+100){
      context.beginPath();
      context.strokeStyle = "gray";
      context.moveTo(x,0);
      context.lineTo(x,800);
      context.stroke(); 
    }

    // Creates row lines for grid (only used as a guide to visualize the grid)
    for (let y=100; y < grid.height; y=y+100){
      context.beginPath();
      context.strokeStyle = "gray";
      context.moveTo(0,y);
      context.lineTo(800,y);
      context.stroke(); 
    }

   // for loop that will populate the grid with cell objects   
    for(let i=0;i<Math.pow(gridSize,2);i++){
      cell = {}; // set cell to an empty object
      cell.sx = xPos; // set cell's x position to xPos
      cell.sy = yPos; // set cell's y position to yPos
      cell.image = populator(cell.sx + 3, cell.sy + 3); // set the image of the cell to a randomly generated image drawn from the populator function. The 3 value is added to both the cell's x and y to make the images appear more centered in the cell
      cell.width = Math.floor(grid.width/gridSize); // set cell object width
      cell.height = Math.floor(grid.height/gridSize); // set cell object height

      grid.push(cell); // pushes cell object into grid array

      // This will ensure that if the cell being added is at the end of the grid's width, then it will restart from x=0 and down the next row
      xPos += cell.width;
      if(xPos >= grid.width){
        xPos = 0;
        yPos += cell.height;
      }
    }

    mouse = {x : 0, y : 0} // set initial mouse (x,y) position
  }

   // function that generates a random image from the tileImgs array
   function randomImage(){
   // set tileImgs to an array of [images]
    tileImgs = [
      ['https://res.cloudinary.com/react-game/image/upload/v1505888751/dark_jrlqiz.png'],
      ['https://res.cloudinary.com/react-game/image/upload/v1505888750/earth_hqs6wb.png'],
      ['https://res.cloudinary.com/react-game/image/upload/v1505888750/fire_rfncey.png'],
      ['https://res.cloudinary.com/react-game/image/upload/v1505888750/light_fzmtsd.png'],
      ['https://res.cloudinary.com/react-game/image/upload/v1505888750/physical_mqziht.png'],
      ['https://res.cloudinary.com/react-game/image/upload/v1505888750/thunder_wjea6m.png'],
      ['https://res.cloudinary.com/react-game/image/upload/v1505888750/water_t1r4fs.png']
    ];    

    return tileImgs[Math.floor(Math.random() * tileImgs.length)] // returns a randomly selected image from the tileImgs array
  }

  // draws the randomly generated image returned from the randomImage function onto the canvas at coordinates (x,y)
  function populator(x,y) {
    var img = new Image(); // instantiate a new image object
    img.src = randomImage(tileImgs);  // set the source of the new image object to a randomly generated image via the randomImage function 


    img.onload = function() {
      context.dr
Diego Mayer
@Chrono79
Oct 02 2017 17:09
@EricHasegawa copy and paste the instructions here, I can't access FCC site right now
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:09

Sum all the prime numbers up to and including the provided number.

A prime number is defined as a number greater than one and having only two divisors, one and itself. For example, 2 is a prime number because it's only divisible by one and two.

The provided number may not be a prime.

@Chrono79
Amit Patel
@AmitP88
Oct 02 2017 17:09
@sjames1958gm
function populator(x,y) {
    var img = new Image(); // instantiate a new image object
    img.src = randomImage(tileImgs);  // set the source of the new image object to a randomly generated image via the randomImage function 

    // function that draws the image at the cell's x and y once the image file has finished loading
    img.onload = function() {
      context.drawImage(img, x,y);
    }

    return img.src; // return the source of the new image object
  }


  //  Cell Swap: When the user clicks (click1) on a cell (Cell1) & clicks (click2) on any adjacent cell (Cell2), the position of Cell1 becomes Cell2 and the position of Cell2 becomes Cell1.

  var swap_container = []; // Array that will contain two elements: The first cell the user clicked on, and the second cell the user clicked on. If the two cells are adjacent to each other in the grid, they will be                                swapped

  canvas.addEventListener('click', function(event){
      var rect = canvas.getBoundingClientRect();

      // User clicked cell
      var x = Math.floor(event.clientX - rect.left);
      var y = Math.floor(event.clientY - rect.top);
      var cellW = Math.floor(x/cell.width);
      var cellH = Math.floor(y/cell.height);

      var clickedCell = {
        x : cellW,
        y : cellH,
        image : grid[cellW + gridSize * cellH].image 
      };

    swap_container.push(clickedCell);

    if (swap_container.length > 2) {
      swap_container.length = 2;
    }    
    console.log(swap_container);
    console.log(swap_container.length);
          /* Cells that are adjacent to the user clicked cell */
      // left adjacent cell of user clicked cell
      var x_left = Math.floor((event.clientX - cell.width) - rect.left);
      var cellW_left = Math.floor(x_left/cell.width);

      var adjacentCell_left = {
          x : cellW_left,
          y : clickedCell.y,
          image : grid[cellW_left + gridSize * clickedCell.y].image
      }

      // right adjacent cell of user clicked cell
      var x_right = Math.floor((event.clientX + cell.width) - rect.left);
      var cellW_right = Math.floor(x_right/cell.width);

      var adjacentCell_right = {
        x : cellW_right,
        y : clickedCell.y,
        image : grid[cellW_right + gridSize * clickedCell.y].image
      }

      // top adjacent cell of user clicked cell
      var y_top = Math.floor((event.clientY - cell.width) - rect.top);
      var cellH_top = Math.floor(y_top/cell.width);

      var adjacentCell_top = {
        x : clickedCell.x,
        y : cellH_top,
        image : grid[clickedCell.x + gridSize * cellH_top].image
      }

      // bottom adjacent cell of user clicked cell
      var y_bottom = Math.floor((event.clientY + cell.width) - rect.top);
      var cellH_bottom = Math.floor(y_bottom/cell.width);

      var adjacentCell_bottom = {
        x : clickedCell.x,
        y : cellH_bottom,
        image : grid[clickedCell.x + gridSize * cellH_bottom].image
      }

    // if swap_container[2] is adjacent to swap_container[1], print 1st message

     if ((swap_container[2] = adjacentCell_left) || (swap_container[2] = adjacentCell_top) || (swap_container[2] = adjacentCell_right) || (swap_container[2] = adjacentCell_bottom)) {
           alert("success! the 2nd cell you clicked on is adjacent to the first!");
        } else {
          alert("fail! 2nd clicked on cell is NOT adjacent!");                  
     }

  }, false);

setCanvas();
};
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:09
@sjames1958gm I get a similar error when I change everything to id attribute instead of name. although, when I log the e.target it shows [object HTMLHeadingElement]
Diego Mayer
@Chrono79
Oct 02 2017 17:10
@EricHasegawa Sum all the prime numbers up to and including the provided number.
there, that's one thing you had to fix
Stephen James
@sjames1958gm
Oct 02 2017 17:10
@ahmadabdolsaheb e.target.id should work
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:10
@Chrono79 I think I fixed that part when I used i < num + 1
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:11
@sjames1958gm it still does not :(
class EventVoteDisc extends React.Component {
  constructor(props){
    super(props);
    this.onClick = this.onClick.bind(this);
  }
  onClick(e){
    e.preventDefault();

    var el= e.target;
    console.log("target" + el);
    console.log("option" + e.target.id);
  }
  render(){
    var options = this.props.options.map((option, index )=>
      <div key={index} className="row" >
        <button type="button" className = "btn btn-default custom-button">
        <h3 className="col-xs-6">{option[0]}:</h3>
        <h3 className="col-xs-6">{option[1]}</h3>
        </button>

      </div>);
    return (

      <div onClick={this.onClick} id = "hamsi">
        {options}
      </div>
    );
  }
}
Diego Mayer
@Chrono79
Oct 02 2017 17:11
@EricHasegawa yes, you did, what's the expected value for that number and what do you get?
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:12
When I input 977 it says the result should be 73156, and my result is 72179
Stephen James
@sjames1958gm
Oct 02 2017 17:12
@ahmadabdolsaheb You have to watch for e.target and e.currentTarget
Stephen James
@sjames1958gm
Oct 02 2017 17:13
@ahmadabdolsaheb e.target is what you clicked e.currentTarget is the element you assigned the handler to
In this case you want currentTarget
@EricHasegawa That looks like it is missing the last number 72179 + 977 is 73156
Diego Mayer
@Chrono79
Oct 02 2017 17:15
@EricHasegawa I see what your problem is
you use listOfNum the wrong way
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:16
@sjames1958gm i log both of them for the id and nothing,
class EventVoteDisc extends React.Component {
  constructor(props){
    super(props);
    this.onClick = this.onClick.bind(this);
  }
  onClick(e){
    e.preventDefault();


    console.log("currentTarget" + e.currentTarget.id);
    console.log("e" + e.target.id);
  }
  render(){
    var options = this.props.options.map((option, index )=>
      <div key={index} className="row" >
        <button type="button" className = "btn btn-default custom-button">
        <h3 className="col-xs-6">{option[0]}:</h3>
        <h3 className="col-xs-6">{option[1]}</h3>
        </button>

      </div>);
    return (

      <div onClick={this.onClick} id = "hamsi">
        {options}
      </div>
    );
  }
}
Diego Mayer
@Chrono79
Oct 02 2017 17:16
var listOfPrimes = [];
  for (var i = 2; i < num; i++) {
    listOfNum.push(i); //this array length, is shorter than it needs to be
  }
for (var j =0; j < listOfNum.length; j++) {
  if (test_prime(j) == true) {
    listOfPrimes.push(j);
  }
}
you could use only one loop @EricHasegawa
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:17
//noprotect
function test_prime(n) {
if (n===1)
  {
    return false;
  }
  else if(n === 2)
  {
    return true;
  }else
{
    for(var x = 2; x < n; x++)
    {
      if(n % x === 0)
      {
        return false;
      }
    }
    return true;  
  }
}

function sumPrimes(num) {
 var listOfNum = [];
 var listOfPrimes = [];
  for (var i = 2; i < num + 1; i++) {
    listOfNum.push(i);
  }
for (var j =0; j < listOfNum.length; j++) {
  if (test_prime(j) == true) {
    listOfPrimes.push(j);
  }
}

  var reducedList = listOfPrimes.reduce(function(a,b) {
    return a + b;
  });
   if (test_prime(num) == true) {
     return reducedList + num;
   } else {
     return reducedList;
   }




}



sumPrimes(10);
That's my current code, and it works, but it's quite poorly written
Diego Mayer
@Chrono79
Oct 02 2017 17:18
As I said, you don't need 2 loops
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:18
How can I remove that last if/else statement and make it more concise
Diego Mayer
@Chrono79
Oct 02 2017 17:18
try using only one
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:18
I'll try to fix that after I do this (if I can)
Diego Mayer
@Chrono79
Oct 02 2017 17:19
use for (var j =0; j <= num; j++) {
and you'll realize you don't need listOfNum
Stephen James
@sjames1958gm
Oct 02 2017 17:19
@EricHasegawa Your test_prime in the first attempt should be test_prime(listOfNum(j))
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:19

@sjames1958gm when I delete all the other elements, it seems to work

class EventVoteDisc extends React.Component {
  constructor(props){
    super(props);
    this.onClick = this.onClick.bind(this);
  }
  onClick(e){
    e.preventDefault();


    console.log("currentTarget" + e.currentTarget.id);
    console.log("e" + e.target.id);
  }
  render(){

    return (

      <div onClick={this.onClick} id = "hamsi">
      hello
      </div>
    );
  }
}

so what do you think the problem is, and what should I do if i want to give attributes to each item that i deleted?

Stephen James
@sjames1958gm
Oct 02 2017 17:21
@ahmadabdolsaheb Yes - I told you what the problem was.
With the other elements, when you click then e.target is one of those elements
e.currentTarget will be the div (that is why you had e.target as header element and not div
@ahmadabdolsaheb Use e.target to get what was actually clicked and e.currentTarget to get what had the onClick assigned.
Eric Hasegawa
@EricHasegawa
Oct 02 2017 17:22
I'll keep trying to improve my code for a bit, thanks @Chrono79 @sjames1958gm
CamperBot
@camperbot
Oct 02 2017 17:22
erichasegawa sends brownie points to @chrono79 and @sjames1958gm :sparkles: :thumbsup: :sparkles:
api offline
api offline
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:32
@sjames1958gm thanks for the explanation. I get it now. :)
CamperBot
@camperbot
Oct 02 2017 17:32
ahmadabdolsaheb sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
Stephen James
@sjames1958gm
Oct 02 2017 17:33
@ahmadabdolsaheb :+1:
CamperBot
@camperbot
Oct 02 2017 17:33
api offline
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:43
@AmitP88 hey, how is life? how did job search go for you ?
Amit Patel
@AmitP88
Oct 02 2017 17:46
@ahmadabdolsaheb hey, long time no see! life is ok atm. I'm currently trying (and struggling) to create a unique 3 match game using html canvas and JavaScript, but I'm pushing myself everyday. As for the job search, I haven't really applied in a long time, but I have a friend who's trying to get me in with his company (he's a senior dev there), but he wants me to improve my JS skills and learn React well. I'm hoping my the end of this month I'll have two projects completed- a demo of my game and a ReactJS project completed
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:49
@AmitP88 awesome man. let me know when you get the job tho so we can celebrate :)
Amit Patel
@AmitP88
Oct 02 2017 17:49
@ahmadabdolsaheb for sure :) it might be a while though, JS is kinda kickin' my butt atm, but I'm still trying lol
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:56
@AmitP88 you will do fine Amit
Amit Patel
@AmitP88
Oct 02 2017 17:56
@ahmadabdolsaheb thanks :)
CamperBot
@camperbot
Oct 02 2017 17:56
amitp88 sends brownie points to @ahmadabdolsaheb :sparkles: :thumbsup: :sparkles:
:cookie: 345 | @ahmadabdolsaheb |http://www.freecodecamp.com/ahmadabdolsaheb
Ahmad Abdolsaheb
@ahmadabdolsaheb
Oct 02 2017 17:57
@AmitP88 btw when you are done with your projects, share them with me, I wanna check them out ;)
Amit Patel
@AmitP88
Oct 02 2017 17:57
@ahmadabdolsaheb here's what I got so far for my 3 match game: https://codepen.io/AmitP88/pen/pWyaNY?editors=0010
I'm currently trying to figure out how to swap two adjacent indeces in the 2d array
I've had to scrap my old code and use a 2d array because my old code was overly complicated lol
Stephen James
@sjames1958gm
Oct 02 2017 18:32
@AmitP88 Try to minimize working with canvas coordinates, and work with your 2d array i/j
Have a function that converts mouse click / canvas to i/j
Amit Patel
@AmitP88
Oct 02 2017 18:33
@sjames1958gm ah ok, that makes sense. Let me see if I can come up with that
imperial-isms
@imperial-isms
Oct 02 2017 18:48
Does anyone have experience deploying their front-end projects on Heroku?
I just have .html, .css. and .js files
Jason Luboff
@JLuboff
Oct 02 2017 18:50
I've only deployed backend projects with Heroku
imperial-isms
@imperial-isms
Oct 02 2017 18:50
What about git?
Jason Luboff
@JLuboff
Oct 02 2017 18:50
What about it?
imperial-isms
@imperial-isms
Oct 02 2017 18:50
I’m trying to figure out the best way to deploy my calc and pomodoro timer
Jason Luboff
@JLuboff
Oct 02 2017 18:51
Well unless you're going to create the backend too with nodejs, I don't think you can use heroku
imperial-isms
@imperial-isms
Oct 02 2017 18:51
I was thinking that when I was looking at buildpacks on Heroku’s website
Any suggestions?
Jason Luboff
@JLuboff
Oct 02 2017 18:52
just use codepen?
imperial-isms
@imperial-isms
Oct 02 2017 18:53
I’m trying to move away from Codepen and learn these other tools
piteto
@piteto
Oct 02 2017 18:53
@imperial-isms I used these instructions to deploy to github: https://forum.freecodecamp.org/t/use-github-static-pages-to-host-your-front-end-projects/18396
found an easier way to do it after practicing, but it's a decent starting point
imperial-isms
@imperial-isms
Oct 02 2017 18:54
Okay cool
Thanks, bud.
I’ll check yours out first and then go from there
Amit Patel
@AmitP88
Oct 02 2017 19:01
@sjames1958gm you know what, I think I'm going to ditch using Canvas and try using Phaser.js. I've seen a ton of games made with it. Maybe I'll have better luck doing that
Gyllenbern
@Gyllenbern
Oct 02 2017 19:08
Hey guys! I have tried to find a way for my users to save data in form of text inside a content page for too long now and figured I would ask here. Would really appreciate if someone had an idea. I have looked at normal forms, but does not seem to be the best solution.
Private notes that is.
Stephen James
@sjames1958gm
Oct 02 2017 19:16
@AmitP88 Good luck
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 19:19
hello everyone
@Gyllenbern hey, wanna create the html part or the send part message part?
Amit Patel
@AmitP88
Oct 02 2017 19:23
@sjames1958gm thanks :)
CamperBot
@camperbot
Oct 02 2017 19:23
amitp88 sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8506 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Stephen James
@sjames1958gm
Oct 02 2017 19:34
@AmitP88 :+1:
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 19:39
so I was looking for an url validator came across this
/^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i
seems 2 much for me
correct me if Im wrong and thanks for looking into it
there's a module for it nm, there's a module for everything for what it seems
korzo
@korzo
Oct 02 2017 19:45
@tiagocorreiaalmeida Still better than this email validator
7317i52F22B049F8234DC.png
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 19:46
hole
holy
where did you get that from?
I run into it once I was looking for email validator and saved it in coding lulz folder :)
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 19:49
now html even does it for us :p
@korzo used to node and express?
korzo
@korzo
Oct 02 2017 19:53
@tiagocorreiaalmeida I think it was for javascript, because PHP has built in validator for email and I don't use Node in production
@tiagocorreiaalmeida I think this one should do the trick in JS
/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
piteto
@piteto
Oct 02 2017 19:55

This is the one used in HTML5 forms:

/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/

http://w3c.github.io/html/sec-forms.html#valid-e-mail-address

Lucci Paula
@luccipaula
Oct 02 2017 19:56
Hi peoples! I'm on the "Wherefore art thou" algorithm challenge where I'm comparing arrays of objects and returning the ones that match the second argument of the function. I've got it working for when the second argument only has one key:value pair, but how should I go about making it work for multiple key:value pairs? I'm still a bit confused on how to access the values...
function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line

  // collection = Array
  // obj = Object
  // prop = property
  // collection[obj] = { first: "Romeo", last: "Montague" }
  // collection[obj][prop] = "Capulet"

  Object.keys(collection).forEach(function(obj) {
    for (var prop in collection[obj]) {
      if (collection[obj].hasOwnProperty(prop) && collection[obj][prop] == source[prop]) {
        arr.push(collection[obj]);
      }
    }
  });

  // Only change code above this line
  return arr;
}

whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 19:56
@korzo I used a module it does the trick for me :package:
:p
korzo
@korzo
Oct 02 2017 19:57
@caixeta-paula Source can have more than one property
Lucci Paula
@luccipaula
Oct 02 2017 19:59
@korzo Yes, I'm just not sure how to access multiple properties in source
I feel like I may be close
korzo
@korzo
Oct 02 2017 19:59
@caixeta-paula Also collection is array
Lucci Paula
@luccipaula
Oct 02 2017 20:00
@korzo Yes I understand that
Henry
@GitHub-Henry
Oct 02 2017 20:00
@imperial-isms Heroku is better to learn if you want to host a full stack app
Lucci Paula
@luccipaula
Oct 02 2017 20:01
Collection is an array of objects, and source is an object
korzo
@korzo
Oct 02 2017 20:02
@caixeta-paula Youy can use forEach directly on collection
@caixeta-paula Also you have to loop over source inside callback and test, if all source properties are in obj
Stephen James
@sjames1958gm
Oct 02 2017 20:02
@caixeta-paula You'll want to loop on the properties on source not on collection[obj]
And only push if all are valid
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 20:19
everytime I post here a question 2 seconds after I see the solution no idea why
Jason Luboff
@JLuboff
Oct 02 2017 20:19
Oh man... Tom Petty died
Gersho
@Gersho
Oct 02 2017 20:20
googles
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 20:28
app.get("/shortit/:link",(request,response)=>{
    var original_url = request.params.link;
    var obj = new Object();
    urlShort.findOne({text:original_url}).then((link)=>{
        //url doesnt exist proceed to createOne
        if(!link){
        urlShort.findOne({}, {}, { sort: { 'key' : -1 } }).then((doc) =>{
                return new Promise ((resolve,reject)=>{
                if(doc){
                    resolve(doc.key+1);
                }
                resolve(1);
                });
            }).then((keyUpdate)=>{
                var shortLink = new urlShort({
                    text:original_url,
                    key:keyUpdate
                });
                  shortLink.save();
            }).then((doc)=>{
                console.log(doc);
                response.send(doc);
            });
        }
        //url exists return the existent
        obj.original_url = original_url;
        obj.short_url = link.key;
        response.send(obj);
    }).catch((err)=>{
        response.send(err);
    });
});
anyidea why does the console.log(doc) returns undefined?
Jason Luboff
@JLuboff
Oct 02 2017 20:31
Is that mongoose?
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 20:31
yeah
everything works perfectly
it does the insert into the db with the correct key
but the res.send
doesnt seems to be working
Jason Luboff
@JLuboff
Oct 02 2017 20:32
What if you change doc to something else?
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 20:33
allready tried to docsave
but maybe didnt refrshed
as it should
let me try again
happens the same
im using a then cause .save() returns a promise as far as I know
Jason Luboff
@JLuboff
Oct 02 2017 20:34
I don't like mongoose, so I'm not sure :D
imperial-isms
@imperial-isms
Oct 02 2017 20:39
Anyone know why my timer won’t stack properly in Safari? It works in Chrome.
imperial-isms
@imperial-isms
Oct 02 2017 20:47
…also, very open to feedback of any kind.
Gersho
@Gersho
Oct 02 2017 20:48
@imperial-isms i like the circle idea, but isn't a pomodoro supposed to be in minutes rather than seconds ?
imperial-isms
@imperial-isms
Oct 02 2017 20:48
Yeah, just have it set to seconds so I make sure it’s working properly without having to wait so long.
“so long"
Gersho
@Gersho
Oct 02 2017 20:49
oh ok, well i like the circle then (it is a bit confusing at first, but nice)
imperial-isms
@imperial-isms
Oct 02 2017 20:49
Thank you
Gotta learn more about UI/UX so I can make desirable actions very apparent
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 20:53
@JLuboff used to express?
got a little issue here
Jason Luboff
@JLuboff
Oct 02 2017 20:53
Yes
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 20:53
app.get("/:key",(request,response)=>{
    urlShort.findOne({key:request.params.key.toString()}).then((link)=>{
         response.send(link.text);
    }).catch((error)=>{
        response.send({errorMessage:"The Url doesn't exist registed in the database"});
    });
});
this will return this
means works perfectly
but if I change send to redirect
it returns the link in the url
and doesnt go into it
like
Jason Luboff
@JLuboff
Oct 02 2017 20:55
What do you want it to do?
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 20:55
redirect the user into the link that comes from the database
doing the url shortner thing
Jason Luboff
@JLuboff
Oct 02 2017 20:56
So why not redirect to the url?
response.redirect(link.text)
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 20:57
app.get("/:key",(request,response)=>{
    urlShort.findOne({key:request.params.key.toString()}).then((link)=>{
         response.redirect(link.text);
    }).catch((error)=>{
        response.send({errorMessage:"The Url doesn't exist registed in the database"});
    });
});
will show you wahat happens in the browser
image.png
gets into the catch everytime I use response.redirect
Jason Luboff
@JLuboff
Oct 02 2017 20:58
Oh. Well seems like its a mongoose issue then. I like vanilla mongo, mongoose has never worked right for me :P
Do you have a url in your database that corresponds to that?
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 20:59
image.png
hum yeah, strange I got all the info correct
I can even send the link.text and it works
but if I change to redirect
Jason Luboff
@JLuboff
Oct 02 2017 20:59
@tiagocorreiaalmeida So key is a number?
@tiagocorreiaalmeida You're searching for key: "number" instead of key: number
Don't turn your request.params.key into a string, turn it into a number
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:01
still doesnt work, this thing hates me :D
I turned to string for some reason before but can't remember why so it was a mistake, but stills doesnt work
Jason Luboff
@JLuboff
Oct 02 2017 21:02
Are you implicitly turning it into a number?
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:02
var urlShort = mongoose.model("url",{
    text:{
        type:String,
        required: true,
        minlength: 1,
        maxlength: 256,
        trim:true
    },
    key:{
        type:Number,
        default:0
    }
});
Jason Luboff
@JLuboff
Oct 02 2017 21:03
Meaning in this line urlShort.findOne({key:request.params.key.toString()
I believe its a string by default, so you need to change it to a number
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:03
was thinking about that right now
I need to turn it into an umber
and not string
Jason Luboff
@JLuboff
Oct 02 2017 21:04
Yes
I would just do key: Number(request.params.key)
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:05
app.get("/:key",(request,response)=>{
    urlShort.findOne({key: Number(request.params.key)}).then((link)=>{
        response.send(link.text);
    }).catch((error)=>{
        response.send({errorMessage:"The Url doesn't exist registed in the database"});
    });
});
image.png
if I change to redirect happens the same thing
Jason Luboff
@JLuboff
Oct 02 2017 21:06
You sure you saved after changing it to redirect?
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:06
I got nodemon running and yes I saved I even stoped it and runned again
looks so strange
Jason Luboff
@JLuboff
Oct 02 2017 21:07
ok, ya nodemon should have handled it. But that shows that its going into the "then" block
Not sure why response.redirect(link.text); wouldn't work though..
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:07
I updated t othis
app.get("/:key",(request,response)=>{
    response.redirect("www.google.com");
});
and not evne this runs xd
Jason Luboff
@JLuboff
Oct 02 2017 21:08
What happens?
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:08
I think bash bugged
sec
time to get back to the friendly powershell
still get this
Jason Luboff
@JLuboff
Oct 02 2017 21:11
maybe redirect isn't what we want..hold on
Gersho
@Gersho
Oct 02 2017 21:12

i think bash bugged
time to get back to the friendly powershell

2017, where bash is at fault and powershell is "friendly"

Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:12
:D
it bugged sometimes in the last days that's why
Jason Luboff
@JLuboff
Oct 02 2017 21:12
@tiagocorreiaalmeida Nope... redirect is definitely what we want. Thats what I used
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:17
crap no idea why this doesnt work
doesnt seems related to mongoose
cause it didnt worked without a db request
Jason Luboff
@JLuboff
Oct 02 2017 21:18
Upload to glitch then you can share the editor
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:20
another question @JLuboff
im using this to create urls
app.get("/shortit/:link",(request,response)=>{
how do you handle https and http passed as link?
in the link*
Jason Luboff
@JLuboff
Oct 02 2017 21:23
I used this app.get(/\/?(http:\/\/|https:\/\/)(.*)/, function(req, res){ which then I accessed req.params[0] and req.params[1] but...I don't remember why lol
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:28
cause 0 has the http or https
and 1
has the rest of link
good one tought
Jason Luboff
@JLuboff
Oct 02 2017 21:29
Ya I figured that much lol
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:29
really goodone
did you handled getting like some input without http or https?and if so how?sorry to bother newbie to the backend things
Jason Luboff
@JLuboff
Oct 02 2017 21:31
I don't think so
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:33
can you give it a quick look?and sorry to bother you somuch
Ronique Ricketts
@RoniqueRicketts
Oct 02 2017 21:34
dont worry. he likes being bothered. He is familiar with this level of abuse.
Jason Luboff
@JLuboff
Oct 02 2017 21:35
:(
Send over your github repo
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:35
app.get("/:wrong",(request,response)=>{
    response.send({errorMessage:"Wrong Url Input be sure to set HTTP or HTTPS protocol"});
});
image.png
gets the trick done
Gersho
@Gersho
Oct 02 2017 21:36
he needs some training about being bothered too, kids are on another level of bothering
Jason Luboff
@JLuboff
Oct 02 2017 21:36
@tiagocorreiaalmeida If you want a route that handles everything else, you can use app.user('/*'...
Just place it after all your other routes
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:36
cool didnt knew
Jason Luboff
@JLuboff
Oct 02 2017 21:36
@Gersho My patiences will be tried many times I'm sure
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:37
@JLuboff this part is ok for the input I need to validate the link, and got an issue on a promise but that isnt the case right now about the redirect im going to upload to github and then send oyu a link if its ok?
Jason Luboff
@JLuboff
Oct 02 2017 21:37
Ya
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:37
cool
Jason Luboff
@JLuboff
Oct 02 2017 21:38
I mean...I'm awful at debugging others peoples code..but shit, we'll see what happens :P
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:38
ahaahha np evne if you dont find a solution im gratefull just by taking your time int oit
Jason Luboff
@JLuboff
Oct 02 2017 21:41
@Gersho Lol It just makes life easy!
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:43
you read the story to the right or down? :D
to right nm
Gersho
@Gersho
Oct 02 2017 21:44
12
34
56
Jason Luboff
@JLuboff
Oct 02 2017 21:45
@tiagocorreiaalmeida So what are you trying to get at right now? Currently you have the route for adding the url to the database, but what we actually want to return from that route is the original url and the shortened url in an object to the browser (which is were perhaps I was messing up by suggesting redirect, my mistake, I was getting ahead of you I think). We then want a second route app.get(/[\d]/.,.. (or whatever the proper regex would be to find digits) which will find the number in the db and then redirect us at that point
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:47
the strange thing was that before we add this and all my routes where differente
```
app.get("/:key",(request,response)=>{
    urlShort.findOne({key: Number(request.params.key)}).then((link)=>{
        response.send(link.text);
    }).catch((error)=>{
        response.send({errorMessage:"The Url doesn't exist registed in the database"});
    });
});
```
and it didnt work
but let me get a number and see what Happens
image.png
app.get(/[\d]/,(request,response)=>{
    response.redirect("www.google.com");
});
Jason Luboff
@JLuboff
Oct 02 2017 21:50
my number regex deal there may not have been correct
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:52
app.get(/\d+/,(request,response)=>{
    response.redirect("www.google.com");
});
still same issue
did you tied to run this locally?
might be something buggy with the redirect?
Jason Luboff
@JLuboff
Oct 02 2017 21:54
I didn't run it, just looked at your code
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 21:55
there's smething buggy in this im running a response .send in the main routright now to see if is there any issue and it stills rendering my previous html file
Jason Luboff
@JLuboff
Oct 02 2017 21:58
Try a different browser
Moisés Man
@moigithub
Oct 02 2017 21:59
routes order matters....
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 22:00
they do but if I have 0 response.render it can't run it
strange thing
Long Nguyen
@longnt80
Oct 02 2017 22:01
I found this JS cheatsheet which is pretty helpful: https://github.com/mbeaudru/modern-js-cheatsheet
Moisés Man
@moigithub
Oct 02 2017 22:01
add console.log....
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 22:02
this is my code ```
const express = require("express");
const bodyParser = require("body-parser");
const {ObjectID} = require("mongodb");


var app = express();
app.set("view engine","html");
app.use(express.static(__dirname + "/views"));
var port = process.env.PORT || 3000;

var {mongoose} = require("./db/mongoose");
var {urlShort} = require("./models/url");

app.use(bodyParser.json());

app.get("/",(request,response)=>{
    console.log("hi");
    response.send("www.google.com");
}); 
app.listen(port,()=>{
    console.log(`Running on port ${port}`);
});
doesnt even run the console.log there
this is really strange
and still renders the html
nm will stop for today , thanks all for the help
Moisés Man
@moigithub
Oct 02 2017 22:04
instead of get /
add something.. app.get ('/boo')
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 22:05
quick question @moigithub do you see any error in this code
app.get("/:key",(request,response)=>{
    urlShort.findOne({key: Number(request.params.key)}).then((link)=>{
        response.send(link.text);
    }).catch((error)=>{
        response.send({errorMessage:"The Url doesn't exist registed in the database"});
    });
});
instead of send I mean redirect
my redirect is just setting the atuall link+ plus another link like localhost:3000/www.google.com
Moisés Man
@moigithub
Oct 02 2017 22:06
relative vs absolute path.. if ur url dont have // on it it will be treaten as relative thats why its appended localhost etc
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 22:07
so if it has http://
the problem willbe solved in this case?
Moisés Man
@moigithub
Oct 02 2017 22:09
test it...
res.redirect("https://www.google.com")
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 22:11
does the trick didnt knew about this sorry t obother so much and thanks all for the effort have a rest of a good day
Lucci Paula
@luccipaula
Oct 02 2017 23:09
I feel so dumb for being stuck on this seemingly simple algorithm for hours... I don't understand how to make sure that each object in "collection" contains ALL the properties of "source"
function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line


  collection.forEach(function(obj) {
    for (var prop in source) {
      if (obj.hasOwnProperty(prop)) {
        // ??
      }
    }
  });

  // Only change code above this line
  return arr;
}

whatIsInAName([{ "a": 1, "b": 2 }, { "a": 1 }, { "a": 1, "b": 2, "c": 2 }], { "a": 1, "b": 2 });
Whenever I try to get an output I always get every object, because they all contain the first property
Thank you to @korzo and @sjames1958gm for trying to help me earlier
CamperBot
@camperbot
Oct 02 2017 23:10
caixeta-paula sends brownie points to @korzo and @sjames1958gm :sparkles: :thumbsup: :sparkles:
:cookie: 568 | @korzo |http://www.freecodecamp.com/korzo
:star2: 8507 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
korzo
@korzo
Oct 02 2017 23:11
@caixeta-paula You should change your condition and return inside condition
After the loop, push obj to arr
@caixeta-paula
    for (var prop in source) {
      if (!obj.hasOwnProperty(prop)) {
        return;
      }
    }
    arr.push(obj);
Lucci Paula
@luccipaula
Oct 02 2017 23:14
@korzo Thank you! I didn't realize that you could just have a plain return statement
CamperBot
@camperbot
Oct 02 2017 23:14
caixeta-paula sends brownie points to @korzo :sparkles: :thumbsup: :sparkles:
api offline
korzo
@korzo
Oct 02 2017 23:14
@caixeta-paula Also your condition is not complete. you have to compare source to obj
Lucci Paula
@luccipaula
Oct 02 2017 23:14
I thought it always had to return a value
korzo
@korzo
Oct 02 2017 23:15
@caixeta-paula In forEach return doesn't matter
@caixeta-paula but .filter is better solution for this challenge as forEach.
Lucci Paula
@luccipaula
Oct 02 2017 23:16
@korzo I thought I was already comparing source to obj?
Tiago Correia
@tiagocorreiaalmeida
Oct 02 2017 23:16
anything I might be missing?
korzo
@korzo
Oct 02 2017 23:16
@caixeta-paula No, it only checks, if obj has property prop
@caixeta-paula It should be
if (obj.hasOwnProperty(prop) && obj[prop] === source[prop] ) {
Lucci Paula
@luccipaula
Oct 02 2017 23:18
@korzo Okay got it, I was about to type that
@korzo Thanks again!
CamperBot
@camperbot
Oct 02 2017 23:18
caixeta-paula sends brownie points to @korzo :sparkles: :thumbsup: :sparkles:
api offline
korzo
@korzo
Oct 02 2017 23:19
@caixeta-paula I think I saw flash of your code :)
for a moment in chat
Lucci Paula
@luccipaula
Oct 02 2017 23:19
@korzo Oh wait, but now it's outputting all of the objects again
Yeah my formatting was wrong lol
korzo
@korzo
Oct 02 2017 23:19
@caixeta-paula Paste your current solution
Lucci Paula
@luccipaula
Oct 02 2017 23:19
Oh wait nvm
Wait yes it's messed up again, ugh
for (var prop in source) {
      if (obj.hasOwnProperty(prop) && obj[prop] == source[prop]) {
        return;
      }
    }
    arr.push(obj);
That's giving me nothing
korzo
@korzo
Oct 02 2017 23:21
@caixeta-paula It's only part of the code inside forEach callback
Lucci Paula
@luccipaula
Oct 02 2017 23:21
function whatIsInAName(collection, source) {
  // What's in a name?
  var arr = [];
  // Only change code below this line


  collection.forEach(function(obj) {
    for (var prop in source) {
      if (obj.hasOwnProperty(prop) && obj[prop] == source[prop]) {
        return;
      }
    }
    arr.push(obj);
  });

  // Only change code above this line
  return arr;
}
korzo
@korzo
Oct 02 2017 23:22
@caixeta-paula Now negate the condition as you are looking for object not having equal property
Lucci Paula
@luccipaula
Oct 02 2017 23:23
negate both?
korzo
@korzo
Oct 02 2017 23:23
@caixeta-paula You have to switch to ||
@caixeta-paula
if (!obj.hasOwnProperty(prop) || !obj[prop] == source[prop]) {
Lucci Paula
@luccipaula
Oct 02 2017 23:24
@korzo Oh okay, that worked
korzo
@korzo
Oct 02 2017 23:24
If obj doesn't have prop OR prop !== source[prop]
Lucci Paula
@luccipaula
Oct 02 2017 23:24
Now I see
korzo
@korzo
Oct 02 2017 23:25
@caixeta-paula Does it pass all tests?
Lucci Paula
@luccipaula
Oct 02 2017 23:26
No, not the Romeo one
whatIsInAName([{ first: "Romeo", last: "Montague" }, { first: "Mercutio", last: null }, { first: "Tybalt", last: "Capulet" }], { last: "Capulet" })
And the editor says "Confusing use of '!'"
korzo
@korzo
Oct 02 2017 23:28
@caixeta-paula Wait a minute, I will try it
Lucci Paula
@luccipaula
Oct 02 2017 23:29
Got it!
It should be obj[prop] != source[prop]
@korzo
korzo
@korzo
Oct 02 2017 23:30
@caixeta-paula OMG :worried:
Lucci Paula
@luccipaula
Oct 02 2017 23:31
@korzo We were looking at the first condition for too long lol
korzo
@korzo
Oct 02 2017 23:31
@caixeta-paula I had it right in description, but got lost in code inside gitter
Lucci Paula
@luccipaula
Oct 02 2017 23:32
@korzo Exactly haha
@korzo Now if I were to try to implement filter instead of forEach, would the two loops inside stay the same?
korzo
@korzo
Oct 02 2017 23:32
@caixeta-paula If it works, you can refactor it, to use .filter instead forEach and save 2 lines
Lucci Paula
@luccipaula
Oct 02 2017 23:33
@korzo Ooh cool I want to try
korzo
@korzo
Oct 02 2017 23:33
@caixeta-paula It require only 2 changes
And 2 deleted lines
Lucci Paula
@luccipaula
Oct 02 2017 23:34
@korzo Hmmm okay
korzo
@korzo
Oct 02 2017 23:35
@caixeta-paula with filter you can return collection directly
And instead push, return true
Lucci Paula
@luccipaula
Oct 02 2017 23:38
Got it
function whatIsInAName(collection, source) {

  var newCollection = collection.filter(function(obj) {
    for (var prop in source) {
      if (!obj.hasOwnProperty(prop) || obj[prop] != source[prop]) {
        return false;
      }
    }
    return true;
  });

  return newCollection;
}
korzo
@korzo
Oct 02 2017 23:39
@caixeta-paula You don't have to store result, but you can return it
Lucci Paula
@luccipaula
Oct 02 2017 23:39
so just return collection?
korzo
@korzo
Oct 02 2017 23:40
@caixeta-paula replace var newCollection = with return
Lucci Paula
@luccipaula
Oct 02 2017 23:40
@korzo Ooh
return is the magic word
korzo
@korzo
Oct 02 2017 23:41
@caixeta-paula .filter() return new array, so you can return result directly
Lucci Paula
@luccipaula
Oct 02 2017 23:42
@korzo That's great, I always thought it was best to store in variables
But I guess that's slower
korzo
@korzo
Oct 02 2017 23:42
@caixeta-paula Yes, also this look prettier :)
Lucci Paula
@luccipaula
Oct 02 2017 23:42
@korzo Very true :)
korzo
@korzo
Oct 02 2017 23:43
@caixeta-paula And now you can refactor this ugly for loop
Lucci Paula
@luccipaula
Oct 02 2017 23:43
@korzo The inside one?
korzo
@korzo
Oct 02 2017 23:43
@caixeta-paula Do you know Array.every() method?
Lucci Paula
@luccipaula
Oct 02 2017 23:43
@korzo No I have never seen it
I will look at the doc
korzo
@korzo
Oct 02 2017 23:44
It does basically the same what your loop does
@caixeta-paula It runs callback on every element and return true, if all callbacks return true, otherwise false
@caixeta-paula So it is what you need inside filter callback (return true/false)
Take keys from source, turn it into array, run every method on this array and in callback compare if passed key is the same on obj and source
Lucci Paula
@luccipaula
Oct 02 2017 23:49
@korzo Does the if statement stay the same?
korzo
@korzo
Oct 02 2017 23:49
@caixeta-paula You don't need if statement anymore
You replace it with return in .every() callback
as you can return comparison
Lucci Paula
@luccipaula
Oct 02 2017 23:50
@korzo Oh okay I see, can I do Object.keys(source).every(...)?
korzo
@korzo
Oct 02 2017 23:50
arr.every(function(el) {
   return el === something;
})
@caixeta-paula Yes :+1:
Lucci Paula
@luccipaula
Oct 02 2017 23:54
I messed up the return statement @korzo
Is it the same as the condition I had before?
korzo
@korzo
Oct 02 2017 23:55
@caixeta-paula You can ditch hasOwnProperty
@caixeta-paula and now condition is opposite, as you want obj, where props IS THE SAME as on source
Lucci Paula
@luccipaula
Oct 02 2017 23:56
return collection.filter(function(obj) {
    Object.keys(source).every(function(prop) {
      return obj[prop] == source[prop];
    })
    return true;
  });
This is giving me all of the objects again
korzo
@korzo
Oct 02 2017 23:57
@caixeta-paula Missing return before Object ;)
Lucci Paula
@luccipaula
Oct 02 2017 23:57
@korzo I forgot the magic word!
korzo
@korzo
Oct 02 2017 23:57
@caixeta-paula remember, every returns true or false
Lucci Paula
@luccipaula
Oct 02 2017 23:58
@korzo Okay I see now, I thought it was limited to inside the callback
Niiiiiice
@korzo Thanks for taking the time to teach me how to simplify this! :D
CamperBot
@camperbot
Oct 02 2017 23:59
caixeta-paula sends brownie points to @korzo :sparkles: :thumbsup: :sparkles:
api offline
Lucci Paula
@luccipaula
Oct 02 2017 23:59
I was feeling really stupid lol