These are chat archives for FreeCodeCamp/HelpJavaScript

30th
Jul 2017
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:00
@jimtryon give example in sec.
@jimtryon sorry, trying to keep up :laughing:
Jim Tryon
@jimtryon
Jul 30 2017 00:00
yeah, I know that feeling being a teacher :)
Stephen James
@sjames1958gm
Jul 30 2017 00:01
@jimtryon
map takes an array and calls your function for each element in the array.
The return value from the call to the function is placed into an array which is the result of the map
Jim Tryon
@jimtryon
Jul 30 2017 00:01
So I want to return a map with an array of values from my object
Stephen James
@sjames1958gm
Jul 30 2017 00:02
function map(array, fn) {
    let array = [];
    for (let i = 0; i < array.length; i++) {
      array.push(fn(array[i]));
    }
   return array;
}
This is what map does, basically
Jim Tryon
@jimtryon
Jul 30 2017 00:03
Ok, I need to call it on the values function that I created
Sample Input:
a:1 b:2 c:3
Sample Output:
1,2,3
John
@AnonymousLords
Jul 30 2017 00:03
@kumquatfelafel What scenarios would you use the two different returns? So what scerios for true: false; and whenValueTrue : etc
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:03

Relatively simple example of map (has a little more functionality, but for your purposes, you don't have to worry about here).

var arr = [1, 2, 3];
arr = arr.map(function (val) {
  return val + 1;
});
console.log(arr) //outputs [2,3,4]

or with ES6

var arr = [1, 2, 3];
arr = arr.map(val => val+1);
console.log(arr) //outputs [2,3,4]
Jim Tryon
@jimtryon
Jul 30 2017 00:05
 return dict.map(values.keys());
actually, key would return 2, 3, 4
John
@AnonymousLords
Jul 30 2017 00:06
@kumquatfelafel I get it, It can return the value if its not a boolean. If it is a boolean, do true or false :D
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:06
@AnonymousLords basically, in this particular case, it wouldn't make sense to use conditional operator, since you're "replacing" the value true with true. Which isn't wrong, but it's not really necessary.
John
@AnonymousLords
Jul 30 2017 00:07
Okay
Since it auto returns true./ false, you dont need a value
Since it is a boolean
But if it were not, you could insert values
Thanks :D
Jim Tryon
@jimtryon
Jul 30 2017 00:11
@kumquatfelafel I still feel lost more than ever on this one…
John
@AnonymousLords
Jul 30 2017 00:11
Think threw it, break it up.
Think simple
“I choose a lazy person to do a hard job. Because a lazy person will find an easy way to do it.” -- Bill Gates
Jim Tryon
@jimtryon
Jul 30 2017 00:13
Let’s see, if I want to return a map with the key/value pairs
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:13
@jimtryon val + 1 : val is an arbitrary variable name provided to reference the current element in array. val + 1 is the operation you are performing on this element, i.e. adding one. What is returned (the element + 1), is added to a new array at same index.
Jim Tryon
@jimtryon
Jul 30 2017 00:13
I would use map on the object to return the keys/values
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:16

Object.keys() returns an array containing the keys, which you can use to access the values of dict.

e.g., dict[Object.keys()[0]] would access the value associated with the first key from Object.keys().

Similarly, dict[Object.keys()[1]] would access value associate with second key.
dict[Object.keys()[2]] would access value associate with third key.

And so on.

Jim Tryon
@jimtryon
Jul 30 2017 00:17
I don’t think Object.keys is working
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:17
@jimtryon post code.
Jim Tryon
@jimtryon
Jul 30 2017 00:18
function values(dict) {
    return dict[Object.keys()];
}
Moisés Man
@moigithub
Jul 30 2017 00:18
Object.keys(dict) // :point_right: [x,y,z]
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:19
:point_up: my bad
Jim Tryon
@jimtryon
Jul 30 2017 00:19
MDN doesn’t show the syntax you have with the object in front
It might be my resources too that are confusing me
Didn’t work, got this error
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:20
@jimtryon dict["blah"] will give you the value associated with dict's property, "blah".
Jim Tryon
@jimtryon
Jul 30 2017 00:20

Failed test #1. Runtime error:
/home/stepic/instances/master-plugins/arena/codejail-629v8vt5/jailed_code:14
console.log(values(obj).join(','));
^

TypeError: Cannot read property 'join' of undefined
at Interface.rl.on (/home/stepic/instances/master-plugins/arena/codejail-629v8vt5/jailed_code:14:28)
at emitOne (events.js:96:13)
at Interface.emit (events.js:188:7)
at Interface._onLine (readline.js:232:10)
at Interface.<anonymous> (readline.js:365:12)
at Array.forEach (native)
at Interface._normalWrite (readline.js:364:11)
at Socket.ondata (readline.js:100:10)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)

Moisés Man
@moigithub
Jul 30 2017 00:20
repost code :)
Jim Tryon
@jimtryon
Jul 30 2017 00:21
function values(dict) {
    return dict[Object.keys(dict)];
}
Moisés Man
@moigithub
Jul 30 2017 00:21
Object.keys return an Array with all keys values
Jim Tryon
@jimtryon
Jul 30 2017 00:21
Is Object.keys not supported? That is one thought
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:21
@jimtryon Note that I had Object.keys(dict)[0].
Jim Tryon
@jimtryon
Jul 30 2017 00:21
I’ve used other ES6 code on the platform
Would that return only the first one @kumquatfelafel?
Moisés Man
@moigithub
Jul 30 2017 00:21
dict={a:1, b:2}
var keyList =  Object.keys(dict)
keyList will be ["a", "b"]
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:21
I was showing that you could say that to get the first key.
@jimtryon yeah
just the first
Joseph
@revisualize
Jul 30 2017 00:22
What challenge?
Jim Tryon
@jimtryon
Jul 30 2017 00:22
Let me try adding the [0]
TypeError: values(...).join is not a function
@revisualize I’m working through the JS platform for Eloquent JS
It looks right to me… I’m probably not seeing something
this was closer @moigithub
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:24
It's not right yet.
Jim Tryon
@jimtryon
Jul 30 2017 00:24
function values(dict) {
    var keyList = Object.keys(dict);
    return keyList;
}

Failed test #1. Cannot check answer. Perhaps output format is wrong.
Input:
a:1 b:2 c:3

Your output:
a,b,c
Correct output:
1,2,3

kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:24
join is function associated with array.
Jim Tryon
@jimtryon
Jul 30 2017 00:24
I need the values though not the keys
Is that just values?
Moisés Man
@moigithub
Jul 30 2017 00:25
well.. now u have the object name.. and the key list.. u need to combine both to get the values
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:25
@jimtryon in any case, this is the start.
var keyList = Object.keys(dict);
Joseph
@revisualize
Jul 30 2017 00:25
BOOM!
Jim Tryon
@jimtryon
Jul 30 2017 00:25
you have to put the keys in a separate var and return it? I can’t just do a return
Stephen James
@sjames1958gm
Jul 30 2017 00:26
@jimtryon So you have an array of keys
for each key push the corresponding value to another array
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:27
@jimtryon Your code posted using the values() function was correct. Though, as stated earlier, it might have been unhappy with it for one reason or another.
CallMeOrange
@EgnaroDev
Jul 30 2017 00:27
@sjames1958gm Can you take a look at my code for Roman Numeral Converter? I completed it but probably too simple...
Stephen James
@sjames1958gm
Jul 30 2017 00:27
@EgnaroDev sure
CallMeOrange
@EgnaroDev
Jul 30 2017 00:27
function convertToRoman(num) {
 // var romanNum = ["I","IV","V","IX","X","XL","L","XC","C","CD","D","CM","M"];
  //var number = [1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000];

  var answer = "";
  for (var i = num; i >= 0; i--){
    if (1000 <= num) {num = num - 1000, answer += "M";}
    else if (900 <= num) num = num - 900, answer += "CM";
    else if (500 <= num) num = num - 500, answer += "D";
    else if (400 <= num) num = num - 400, answer += "CD";
    else if (100 <= num) num = num - 100, answer += "C";
    else if (90 <= num) num = num - 90, answer += "XC";
    else if (50 <= num) num = num - 50, answer += "L";
    else if (40 <= num) num = num - 40, answer += "XL";
    else if (10 <= num) num = num - 10, answer += "X";
    else if (9 <= num) num = num - 9, answer += "IX";
    else if (5 <= num) num = num - 5, answer += "V";
    else if (4 <= num) num = num - 4, answer += "IV";
    else if (1 <= num) num = num - 1, answer += "I";
    }
  return answer;
}
convertToRoman(10000);
:p
Stephen James
@sjames1958gm
Jul 30 2017 00:27
@EgnaroDev That is much like my first solution. Straightforward.
CallMeOrange
@EgnaroDev
Jul 30 2017 00:28
I was really surprised that I was able to do it with a loop
Jim Tryon
@jimtryon
Jul 30 2017 00:28
function values(dict) {
    var keyList = Object.keys(dict);
    var valList = Object.values(keyList);
    return valList;
}
I was trying to simplify it but that broke
CallMeOrange
@EgnaroDev
Jul 30 2017 00:28
Can you tell me why you used nested loop and what are they used for?
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:29
@jimtryon If it was going to work with values, it would have to be Object.values(dict) like you had before.
CallMeOrange
@EgnaroDev
Jul 30 2017 00:29
After this, I'll probably create a loop without these statements somehow
Jim Tryon
@jimtryon
Jul 30 2017 00:29
It doesn’t like that
Object.values is not a function
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:29
@jimtryon which means that it's not supported.
Stephen James
@sjames1958gm
Jul 30 2017 00:30
@EgnaroDev I am trying to remember why I used nested loops, but I cannot recall.
CallMeOrange
@EgnaroDev
Jul 30 2017 00:30
oh ok
Jim Tryon
@jimtryon
Jul 30 2017 00:30
@kumquatfelafel so I need to find a workaround?
CallMeOrange
@EgnaroDev
Jul 30 2017 00:30
I guess I can go look at my old solution by my old account
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:30
@jimtryon Which is why we need to... yep!
CallMeOrange
@EgnaroDev
Jul 30 2017 00:31
wow I'm surprised...
function convertToRoman(num) {

  var number = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ];
  var romanNumeral = [ 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I' ];


  var roman='';

  for (var i = 0; i<number.length; i++){
    while(number[i]<=num){
      roman += romanNumeral[i];
       num -= number[i];
    }
  } 
  return roman;
}

convertToRoman(9);
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:31

In any case, this so far is good.
var keyList = Object.keys(dict);

This gives us an array of the keys found in dict

This is something we can use.
CallMeOrange
@EgnaroDev
Jul 30 2017 00:32
That solution is really good lol, I was able to code really better but I can't imagine old me to create that solution
Stephen James
@sjames1958gm
Jul 30 2017 00:32
@EgnaroDev That's it.
CallMeOrange
@EgnaroDev
Jul 30 2017 00:32
@sjames1958gm Is it like yours?
Since that solution was created by old me so thats mean it is my solution (evil laughing) :/
Stephen James
@sjames1958gm
Jul 30 2017 00:33
@EgnaroDev It was like one of my solutions.
Here is where I used a single array
function convertToRoman(num) {
    var result = "";
    var cvrt = [[1000, "M"], [900, "CM"], [500, "D"], [400, "CD"], 
              [100, "C"], [90, "XC"], [50, "L"], [40, "XL"], [10, "X"], 
              [9, "IX"], [5, "V"], [4, "IV"], [1, "I"]];

  var i = 0;
  while (num > 0) {
    if (num >= cvrt[i][0]) {
      result += cvrt[i][1];
      num -= cvrt[i][0];
    }
    else i++;
  }

  return result;
}
CallMeOrange
@EgnaroDev
Jul 30 2017 00:33
hm..
what's else for?
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:33
@EgnaroDev by the way, it might interest you to know... :p
https://www.codewars.com/kata/51b62bf6a9c58071c600001b
Stephen James
@sjames1958gm
Jul 30 2017 00:33
Don't go to the next array entry until the number is less than the current decimal value
Jim Tryon
@jimtryon
Jul 30 2017 00:33
    return keyList.map(function(dict));
getting closer
John
@AnonymousLords
Jul 30 2017 00:34
@sjames1958gm Clever
CallMeOrange
@EgnaroDev
Jul 30 2017 00:34
@sjames1958gm oh ok
kyu 4??
Stephen James
@sjames1958gm
Jul 30 2017 00:34
@jimtryon return keyList.map(function(key)); the value passed to the function is the key value
CallMeOrange
@EgnaroDev
Jul 30 2017 00:34
@kumquatfelafel One time, my friend and I accidently cheated to solve one of kyu 4's then somehow doubled our points...
Stephen James
@sjames1958gm
Jul 30 2017 00:35
I completed a 3 kyu today that pushed me to 4 kyu
CallMeOrange
@EgnaroDev
Jul 30 2017 00:35
Nice
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:35
@EgnaroDev :o
I am just shocked and appalled!
:p
CallMeOrange
@EgnaroDev
Jul 30 2017 00:35
lol
Jim Tryon
@jimtryon
Jul 30 2017 00:35
unexpected token
return keyList.map(function(keyList));
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:36
@jimtryon I would use key, like @sjames1958gm does.
keyList.map(function(key));
Stephen James
@sjames1958gm
Jul 30 2017 00:36
return keyList.map(function(key) { Here you would return the value from dict for the key });
John
@AnonymousLords
Jul 30 2017 00:36
:point_up: July 29, 2017 7:56 PM @kumquatfelafel would it be rev === str ? valueWhenTrue : valueWhenFalse; (have semi-colons on the end) Or just left without any? Just making sure
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:36
so at moment though we have a function that doesn't actually do anything
CallMeOrange
@EgnaroDev
Jul 30 2017 00:36
@kumquatfelafel thanks, solved it xD
CamperBot
@camperbot
Jul 30 2017 00:36
egnarodev sends brownie points to @kumquatfelafel :sparkles: :thumbsup: :sparkles:
:cookie: 554 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
CallMeOrange
@EgnaroDev
Jul 30 2017 00:37
All I did is to copy my code then var num = number
:trollface:
John
@AnonymousLords
Jul 30 2017 00:37
:clap:
@EgnaroDev (MC) :point_up: July 29, 2017 8:36 PM
CallMeOrange
@EgnaroDev
Jul 30 2017 00:38
you can have semi-colons on the end
Jim Tryon
@jimtryon
Jul 30 2017 00:38
function values(dict) {
    var keyList = Object.keys(dict);
    return keyList.map(function(key) {
});
John
@AnonymousLords
Jul 30 2017 00:38
Doe sit have to?
Jim Tryon
@jimtryon
Jul 30 2017 00:38
Unexpected token
CallMeOrange
@EgnaroDev
Jul 30 2017 00:39
return (condition) ? true; : false;
@AnonymousLords Well maybe... unless there is an error
John
@AnonymousLords
Jul 30 2017 00:39
@EgnaroDev would it be rev === str ? valueWhenTrue : valueWhenFalse; or rev === str ? valueWhenTrue : valueWhenFalse (;)
CallMeOrange
@EgnaroDev
Jul 30 2017 00:39
you need return
John
@AnonymousLords
Jul 30 2017 00:40
ik i was just checking the false/ true part
CallMeOrange
@EgnaroDev
Jul 30 2017 00:40
oh
Whats different?
Stephen James
@sjames1958gm
Jul 30 2017 00:40
@jimtryon
function values(dict) {
    var keyList = Object.keys(dict);
    return keyList.map(function(key) {
       // here the function code goes
    });
}
John
@AnonymousLords
Jul 30 2017 00:40
The ;
CallMeOrange
@EgnaroDev
Jul 30 2017 00:40
oh why ()?
Jim Tryon
@jimtryon
Jul 30 2017 00:40
@sjames1958gm I don’t have a function to put in there
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:40
@AnonymousLords it's good practice to include the ; at the end.
John
@AnonymousLords
Jul 30 2017 00:41
Okay thanks @kumquatfelafel @EgnaroDev
CamperBot
@camperbot
Jul 30 2017 00:41
anonymouslords sends brownie points to @kumquatfelafel and @egnarodev :sparkles: :thumbsup: :sparkles:
:warning: anonymouslords already gave egnarodev points
:cookie: 555 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
Stephen James
@sjames1958gm
Jul 30 2017 00:41
@jimtryon So you want to go from an array of keys to an array of values?
CallMeOrange
@EgnaroDev
Jul 30 2017 00:41
imagine doing this return (con) ? "This is true" : "This is false";
Jim Tryon
@jimtryon
Jul 30 2017 00:41
@sjames1958gm Yeah
CallMeOrange
@EgnaroDev
Jul 30 2017 00:41
Never mind, I thought it would be confusing
@kumquatfelafel Can I see your code for Roman Numeral Converter?
Jim Tryon
@jimtryon
Jul 30 2017 00:41

Failed test #1. Cannot check answer. Perhaps output format is wrong.
Input:
a:1 b:2 c:3

Your output:
,,
Correct output:
1,2,3

Stephen James
@sjames1958gm
Jul 30 2017 00:42
@jimtryon So map does exactly that
it goes from one array to another.
That function should return the value for the key.
Jim Tryon
@jimtryon
Jul 30 2017 00:43
It’s not returning any of the values
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:43
@EgnaroDev
function convertToRoman(num) {
  var chars = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X","IX","V", "IV", "I"];//Roman numeral "characters"
  var numEq = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1];//numerical equivalents
  var romNum = ""; //initializing roman numeral string
  var multiplier; //determines how many times to repeat character/how much to subtract
  for (var i = 0; i < chars.length, num > 0; i++) {
    romNum += chars[i].repeat(multiplier = Math.floor(num/numEq[i]));
    num -= multiplier * numEq[i];
  }
  return romNum;
}
CallMeOrange
@EgnaroDev
Jul 30 2017 00:43
Nice
Stephen James
@sjames1958gm
Jul 30 2017 00:43
@jimtryon
return dict[key];
Put that as the function body
CallMeOrange
@EgnaroDev
Jul 30 2017 00:44
How long have you do algorithms? @kumquatfelafel
John
@AnonymousLords
Jul 30 2017 00:44
i gtg guys
so tired, just learned how to compact code
today
Jim Tryon
@jimtryon
Jul 30 2017 00:44
function values(dict) {
    var keyList = Object.keys(dict);
    return keyList.map(function(key) {
        return dict[key];
    });
}
thanks @sjames1958gm that was it, so can you explain at a low level how this all works?
CamperBot
@camperbot
Jul 30 2017 00:44
jimtryon sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8193 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Jim Tryon
@jimtryon
Jul 30 2017 00:45
I get the keyList but the part about map(function(key)
Stephen James
@sjames1958gm
Jul 30 2017 00:45
@jimtryon the output array from map is built from each return from the function
so this is mapping from and array of key -> to an array of dict[key]
Jim Tryon
@jimtryon
Jul 30 2017 00:46
I need a visual to see this, wonder if I should do an execution trace to help see what’s going on
We can just do the opposite I think...
Nvm
Stephen James
@sjames1958gm
Jul 30 2017 00:49
@jimtryon
So this is what map is doing under the covers.
It is calling your function, once for each entry in the array (here keylist)
Your function is return dict[key] which is pushed onto the output array and returned.
That is why it is called map because it maps from
function map(array, fn) {
    let array = [];
    for (let i = 0; i < array.length; i++) {
      array.push(fn(array[i]));
    }
   return array;
}
Jim Tryon
@jimtryon
Jul 30 2017 00:50
So basically it’s taking the first key and pairing it with the first value, second key and second value, etc
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:50

map will go through provided array one by one...

key takes the value of the current element. (it doesn't have to be called "key", this is just an arbitrary variable name, like with any function parameter)

dict[key] will access the value of the current element. This is added to an array inside the map function.

Then it goes to the next element, and repeats the same process.

At end, new array that has been derived from old array using specified function... is returned.

:point_up:

Stephen James
@sjames1958gm
Jul 30 2017 00:52
@jimtryon yes
Jim Tryon
@jimtryon
Jul 30 2017 00:52
So it just grabs the key/value on each iteration of the loop
kumquatfelafel
@kumquatfelafel
Jul 30 2017 00:52
yeah
Jim Tryon
@jimtryon
Jul 30 2017 00:52
not separately because that would be inefficient
Stephen James
@sjames1958gm
Jul 30 2017 00:55
@jimtryon Anytime you have an array and want another array where each element depends on the first array think map
Jim Tryon
@jimtryon
Jul 30 2017 00:55
@sjames1958gm thanks for the help!
CamperBot
@camperbot
Jul 30 2017 00:55
jimtryon sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:warning: jimtryon already gave sjames1958gm points
Stephen James
@sjames1958gm
Jul 30 2017 00:55
@jimtryon :+1:
kumquatfelafel
@kumquatfelafel
Jul 30 2017 01:01
@EgnaroDev I've been coding for about a year. I think? Not very good with time-related questions. :p
CallMeOrange
@EgnaroDev
Jul 30 2017 01:02
I see
I thought you coded like 3-5 years since you are so comfortable with methods and so good at algs I guess
Or maybe you focused on algorithms for a year
Dan Stockham
@DanStockham
Jul 30 2017 01:09
Does anyone see anything wrong with this algo for the game of life?
export class Logic {
  static updateCells(prevGrid) {
    const newGrid = prevGrid.map((curr, x, colArr) => {
      const offset = [[-1, -1],[-1, 0],[-1, 1],[0, -1],[0, 1],[1,-1],[1,0],[1,1]];
      return curr.map((curr, y, rowArr) => {
        let count = 0;

        offset.forEach((curr) => {
          if(y + curr[0] >= 0 && y + curr[0] < rowArr.length && x + curr[1] >= 0 && x + curr[1] < colArr.length) {
            // console.log(x + curr[1], y + curr[0]);
            if(colArr[x + curr[1]][y + curr[0]]) {
              count++;
            }
          }
        });

        if(curr === 0) {
          if(count === 3) {
            curr = 1;
          }
        } else if(curr === 1) {
          if(count < 2) {
            curr = 0;
          } else if(count > 3) {
            curr = 0
          }
        }

        return curr;
      });
    });



    return newGrid;
  }
}
kumquatfelafel
@kumquatfelafel
Jul 30 2017 01:09
I'm alright with algorithms. Not great with optimization (at least for now) though.
@EgnaroDev I also was tutoring approx. 6 or 7 hours a day for a while, so that kinda forced me to get very comfortable with what I was doing (even if I'm still not always the greatest at explaining it) :laughing:
Stephen James
@sjames1958gm
Jul 30 2017 01:12
@DanStockham You have an array called curr and you call you map paramerer curr? that is confusing.
Dan Stockham
@DanStockham
Jul 30 2017 01:13
@sjames1958gm curr represents the current element in the grid array.
Stephen James
@sjames1958gm
Jul 30 2017 01:13
@DanStockham Maybe the first curr is rows? and the second is cells?
@DanStockham return curr.map((curr, y, rowArr) => { this line has two curr which have different meaning.
@DanStockham The algorithm looks ok. Maybe more descriptive variable names, Like count could be neighbors?
Dan Stockham
@DanStockham
Jul 30 2017 01:15
@sjames1958gm Good point, I'll make it more descriptive.
@sjames1958gm Thanks
CamperBot
@camperbot
Jul 30 2017 01:15
danstockham sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8194 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Dan Stockham
@DanStockham
Jul 30 2017 01:19
Here is a refactored verison of it:
export class Logic {
  static updateCells(prevGrid) {
    const newGrid = prevGrid.map((row, x, rowArr) => {
      const offset = [[-1, -1],[-1, 0],[-1, 1],[0, -1],[0, 1],[1,-1],[1,0],[1,1]];
      return row.map((cell, y, cellArr) => {
        let count = 0;

        offset.forEach((curr) => {
          if(y + curr[0] >= 0 && y + curr[0] < cellArr.length && x + curr[1] >= 0 && x + curr[1] < rowArr.length) {
            // console.log(x + curr[1], y + curr[0]);
            if(rowArr[x + curr[1]][y + curr[0]]) {
              count++;
            }
          }
        });

        if(cell === 0) {
          if(count === 3) {
            cell = 1;
          }
        } else if(cell === 1) {
          if(count < 2) {
            cell = 0;
          } else if(count > 3) {
            cell = 0;
          }
        }

        return cell;
      });
    });

    return newGrid;
  }
}
It's really weird because some patterns it will skip generations on the test.
kumquatfelafel
@kumquatfelafel
Jul 30 2017 01:22

Gonna code my own things for a bit before my mind melts. :p

Night.

Smai Fullerton
@smaifullerton-wk
Jul 30 2017 01:39

Does anyone know, if I access the values of properties of an object like this:

car.engine.airFilter["cost"]

is there an easy way to return ['car', 'engine', 'airFilter', 'cost'] ?

In a lot of cases, like Lodash's _get, you can pass in a path and it uses split('.') to separate the path out. This would be fine for car.engine.airFilter.cost ... but in the case where you the path is defined using both . notation and [""] or [''] notation, how do you split the path up? Other than using a crappy conditional split with a regex .... there must be an easier and faster way!

Grigor Minasyan
@gogminsam
Jul 30 2017 01:42
Hey guys, I need help in twitch api, I'm doing AJAX inside AJAX inside loop, but second ajax return object without names, here is the codepen link https://codepen.io/gogminsam/full/xLxpvE/ (I am console logging everything)
$(document).ready(function() {
  var urlchn = "https://api.twitch.tv/kraken/channels/";
  var urlstr = "https://api.twitch.tv/kraken/streams/";
  var clientID = "?client_id=x7tzgjtk89a5l72fc3awsd8pe478ws";
  var usernames = [
    "ESL_SC2",
    "ESL_CSGO",
    "OgamingSC2",
    "cretetion",
    "freecodecamp",
    "storbeck",
    "habathcx",
    "RobotCaleb",
    "noobs2ninjas",
    "pink_sparkles",
    "comster404",
    "brunofin",
    "medrybw",
    "monstercat",
    "aces_tv",
    "loserfruit",
    "behkuhtv",
    "fakename",
    "food",
    "medrybw"
  ];

  var usernameswithinfo = [];

  for (i = 0; i < usernames.length; i++) {
    $.ajax({
      url: urlstr + usernames[i] + clientID,
      success: function(data) {
        if (data.stream === null) {
          $.ajax({
            url: urlchn + usernames[i] + clientID,
            success: function(datachn) {
              console.log(datachn);
            }
          });
        } else {
          console.log(data);
        }
      }
    });
  }
});
Smai Fullerton
@smaifullerton-wk
Jul 30 2017 01:58
in the second request you make, usernames[i] is undefined because you no longer have access to it since you make that call as a callback
Grigor Minasyan
@gogminsam
Jul 30 2017 02:00
@smaifullerton-wk Oh ok, so I dont have access to i even though it is inside for loop? I have also tried async: false and it worked, but that method is not good to use i think
@smaifullerton-wk I tried declaring i outside, but it still doesn't work
Smai Fullerton
@smaifullerton-wk
Jul 30 2017 02:03
yes, you'll never have access to that i because it's called as a callback when success is true, so you're outside of that function entirely
can you think of some way you can pass that usernames[i] information to your second function?
Grigor Minasyan
@gogminsam
Jul 30 2017 02:07
@smaifullerton-wk I'll try another method, but do you know why does async: false method work? (even though i is inside the callback?
kumquatfelafel
@kumquatfelafel
Jul 30 2017 02:08
@smaifullerton-wk would it be fair to assume for sake of your question that whatever is inside the bracket is a string literal, not a variable?
Smai Fullerton
@smaifullerton-wk
Jul 30 2017 02:09
yes @kumquatfelafel , always string literal, never variable
kumquatfelafel
@kumquatfelafel
Jul 30 2017 02:10
@smaifullerton-wk 'car.engine.airFilter["cost"]'.match(/\w+/g);
actually sec. Lemme check if w includes numbers :laughing:
Smai Fullerton
@smaifullerton-wk
Jul 30 2017 02:12
@gogminsam check out the difference of the order of how things are returned the first way, and the order of how things are returned with async: false
kumquatfelafel
@kumquatfelafel
Jul 30 2017 02:12
hmm will be close, but also need to account for possible space.
Smai Fullerton
@smaifullerton-wk
Jul 30 2017 02:13
I'm trying to avoid using a regexp @kumquatfelafel just because it's so slow and I have a ton of these paths I want to split :\
kumquatfelafel
@kumquatfelafel
Jul 30 2017 02:16
hmm
Grigor Minasyan
@gogminsam
Jul 30 2017 02:20
@smaifullerton-wk with async: false it bring with the right order, without it it apparently brings with random order, and also repeats the last username few times
Smai Fullerton
@smaifullerton-wk
Jul 30 2017 02:27
yep exactly, the random order is because your program makes a call, then immediately makes the next call without waiting for any previous calls to complete. you get the results returned and it seems random but it's actually in the order that the information was returned from the server. anytime you make calls to a server (or a database, basically any place you get information) you can't guarantee the order in which the results will be returned, which is why ajax things very commonly use that asynchronous callback format to make sure that your results are returned successfully before doing anything with them
Grigor Minasyan
@gogminsam
Jul 30 2017 02:29
@smaifullerton-wk Thank you for your answers, so I guess I will use async: false for this project to get expected results
CamperBot
@camperbot
Jul 30 2017 02:29
gogminsam sends brownie points to @smaifullerton-wk :sparkles: :thumbsup: :sparkles:
:warning: @smaifullerton-wk's account is not linked with freeCodeCamp. Please visit the settings and link your GitHub account.
Smai Fullerton
@smaifullerton-wk
Jul 30 2017 02:33
it will work, but you probably don't want to do that because you have much less control ensuring the order of things and other weird bugs can occur as a result of your requests completing in strange orders. a better way would be to figure out how to pass in usernames[i] to that success callback
John Alcher
@alchermd
Jul 30 2017 02:35
Good day people. Can someone drop some hint on what is used to animate the React Recipe Box? How is the smooth effect as the recipes where clicked done? As well as the modal form when adding/editing a recipe?
Smai Fullerton
@smaifullerton-wk
Jul 30 2017 02:39
@alchermd it's kinda hard to give a hint without just telling you the library to check out .. there's a library for you to check out, want to know the name? :)
Jim Tryon
@jimtryon
Jul 30 2017 02:40
@smaifullerton-wk That’ll give him the answer
kumquatfelafel
@kumquatfelafel
Jul 30 2017 02:41

@smaifullerton-wk there are ways you can find the index of beginning and end, then slice or substr or etc. But I don't know whether doing something like that would, when push comes to shove, actually be faster. The fact that you're dealing with more than one separator also complicates things to some extent.

I tried finding a good performance test that basically does what you've been trying a bunch of different ways (extracting certain words from a string), but the google results so far have been rather underwhelming apples to oranges comparisons.

Smai Fullerton
@smaifullerton-wk
Jul 30 2017 02:43
@kumquatfelafel bummer.. that's what I found too. thanks a lot for looking!
CamperBot
@camperbot
Jul 30 2017 02:43
smaifullerton-wk sends brownie points to @kumquatfelafel :sparkles: :thumbsup: :sparkles:
:cookie: 556 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
John Alcher
@alchermd
Jul 30 2017 02:46
@smaifullerton-wk Please do!
kumquatfelafel
@kumquatfelafel
Jul 30 2017 02:46
@smaifullerton-wk unfortunately, maybe try it a few different ways and just test 'em. I would do it, but I'm too lazy/tired at moment. :p
I think the people who would know the best answer to this aren't on at moment.
Smai Fullerton
@smaifullerton-wk
Jul 30 2017 02:48
@alchermd react-bootstrap
John Alcher
@alchermd
Jul 30 2017 02:52
@smaifullerton-wk I'll check it out.
kumquatfelafel
@kumquatfelafel
Jul 30 2017 02:57
@smaifullerton-wk one question... with a lot of these paths you're performing operation on, will they be mostly the same with perhaps just one or two differing values?
kumquatfelafel
@kumquatfelafel
Jul 30 2017 03:04
actually, nvm
Hemakshi Sachdev
@hemakshis
Jul 30 2017 03:28
How do I add the alarm after the countdown is over in javascript for the Pomodoro project???
Ken Haduch
@khaduch
Jul 30 2017 04:02

@hemakshis - one example of a way to do it is to use the audio interface - this is a sample code for it:

     // Play audio
      var wav = 'http://www.oringz.com/oringz-uploads/sounds-917-communication-channel.mp3';
      var audio = new Audio(wav);
            audio.play();

From the sample project...

JY
@missingway
Jul 30 2017 04:12
hello,anyone can help why I can't pass this?
//求两个数的最大公约数,辗转相除法
var largestFactor = function(a,b){
    var temp; 
    var gys; 
    if(a < b){  
      temp = a;  
      a = b;  
      b = temp;  
    }    
    if(a%b === 0){  
        return b;    
    }else{    
        for(var i=1;i<a;i++){
          if(a%i===0 && b%i===0){
            gys=i;
          }
        } 
    }
    return gys;    
};

//对数字数组升序排列
var mysort = function(a,b){
  return a>b;
};

//利用a*b = [a,b]*(a,b)求数组最小公倍数,每次取两个数先求最大公约数
var smallestCommon = function(arr){
  arr.sort(mysort);
  var min = arr["0"];
  var max = arr["1"];
  var newArr = [];
  for(var i=min;i<=max;i++){
    newArr.push(i);
  }
  var gys = min;
  for(var j=0;j<newArr.length-1;j++){
    var x = gys;
    var y = newArr[j+1];
    var myArr=[];
    myArr.push(x);
    myArr.push(y);

    gys=myArr["0"]*myArr["1"]/largestFactor(myArr["0"],myArr["1"]);
    myArr["0"]=gys;
  }
  console.log(gys);
  return parseInt(gys);
};

smallestCommon([1,13]);
insouciantone
@insouciantone
Jul 30 2017 05:09
Hello everyone, I'm trying to pass the Quote Generator challenge and I can only get the tweet button to tweet a link to the codepen. Can anyone help me figure this out?
korzo
@korzo
Jul 30 2017 05:14
@insouciantone Instead $(this) there have to be $('.twitter-share-button')
insouciantone
@insouciantone
Jul 30 2017 05:16
@korzo Beautiful. Thanks much.
CamperBot
@camperbot
Jul 30 2017 05:16
insouciantone sends brownie points to @korzo :sparkles: :thumbsup: :sparkles:
:cookie: 316 | @korzo |http://www.freecodecamp.com/korzo
kumquatfelafel
@kumquatfelafel
Jul 30 2017 05:22

Agggggghhh!!!

Finally figured this thing out! :laughing:

Forgot to copy array so I've been modifying original, thus for subsequent calls...

Abhinav Mishra
@abhinav-m
Jul 30 2017 05:24
@insouciantone did that fix it?
side note:

var randomQuote = quotes[Math.floor(Math.random() * quotes.length)];
quote = randomQuote.split("randomQuote");
this doesn't make sense..
unless you intend to change it to author and split it like that..
@insouciantone removing the initial href will help not going to twitter with that url.
kumquatfelafel
@kumquatfelafel
Jul 30 2017 05:31
Is there a good function for deep copying 2d or more array?
Jim Tryon
@jimtryon
Jul 30 2017 05:37
@kumquatfelafel From what I found, the best solution is to use .slice()
caneno
@caneno
Jul 30 2017 05:38
hi guys
can you guys help me out with this challenge
kumquatfelafel
@kumquatfelafel
Jul 30 2017 05:38
.slice() only good for 1-dimension unfortunately. I suppose I could put it in a for loop if need be though. @jimtryon thanks
CamperBot
@camperbot
Jul 30 2017 05:38
kumquatfelafel sends brownie points to @jimtryon :sparkles: :thumbsup: :sparkles:
:cookie: 413 | @jimtryon |http://www.freecodecamp.com/jimtryon
caneno
@caneno
Jul 30 2017 05:39
function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var arr1 = arr.sort();
  for(var i = 0; i < arr.length; i++){
    if(arr[i] >= num){
      return arr.indexOf(arr[i]);
    }
  }
}

getIndexToIns([5, 3, 20, 3], 5);
Jim Tryon
@jimtryon
Jul 30 2017 05:39
@kumquatfelafel That is what they recommend, is to put it in a for loop, and even consider using .map() instead of the for
caneno
@caneno
Jul 30 2017 05:39
Iam missing two objective to complete challenge
kumquatfelafel
@kumquatfelafel
Jul 30 2017 05:40
@jimtryon yeah... was trying to look through lodash documentation to see if there's something there, but mind is mush at this point :laughing:
Jim Tryon
@jimtryon
Jul 30 2017 05:40
@kumquatfelafel I definitely can relate to that feeling :P
Abhinav Mishra
@abhinav-m
Jul 30 2017 05:41
@kumquatfelafel try a felafel
;)
kumquatfelafel
@kumquatfelafel
Jul 30 2017 05:41
hmm... Could it be???
...
@abhinav-thinktank arr.felafel() doesn't seem to work. :o
Abhinav Mishra
@abhinav-m
Jul 30 2017 05:41
haha
i meant for the mind is mush part
kumquatfelafel
@kumquatfelafel
Jul 30 2017 05:44
@caneno lemme just find that challenge to... what's it called... my memory.
caneno
@caneno
Jul 30 2017 05:44
@kumquatfelafel Where Do I Belong
Abhinav Mishra
@abhinav-m
Jul 30 2017 05:44
@caneno sort doesnt work like that
caneno
@caneno
Jul 30 2017 05:44
thats the name of the challenge
Abhinav Mishra
@abhinav-m
Jul 30 2017 05:44
@caneno in javascript
wait what..
nvm
@caneno The default sort order is according to string Unicode code points.
@caneno use a compare function as shown
caneno
@caneno
Jul 30 2017 05:46
I am reading the mdn
Abhinav Mishra
@abhinav-m
Jul 30 2017 05:46
@caneno
To compare numbers instead of strings, the compare function can simply subtract b from a. The following function will sort the array ascending (if it doesn't contain Infinity and NaN):
function compareNumbers(a, b) {
  return a - b;
}
yeap, go through it once
caneno
@caneno
Jul 30 2017 05:50
ok I got it but I still need the last objective
function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var arr1 = arr.sort(function(a, b) {
  return a - b;
});
  for(var i = 0; i < arr1.length; i++){
    if(arr1[i] >= num){
      return arr1.indexOf(arr1[i]);
    }
  }
}

getIndexToIns([2, 5, 10], 15);
is not returning enything
anything*
kumquatfelafel
@kumquatfelafel
Jul 30 2017 05:52
@caneno you need a way to return at end if num is greater than all the ones that exist in array.
@caneno also, i is the index of arr1[i], so you don't really need to call indexOf here.
Abhinav Mishra
@abhinav-m
Jul 30 2017 05:57
@caneno won't it be possible to first insert in the array then sort it
@caneno automatically finding it's place
shivam gupta
@shivamg11000
Jul 30 2017 05:58
In reactjs
Scenario: Parent component has 2 props A and B... child component has props A.
Will child component re-render if B props are changed but A props remains unchanged ?
kumquatfelafel
@kumquatfelafel
Jul 30 2017 06:00

@caneno Anywho, so let's think of it this way.
Say I have an array,
arr = [1,2,3];
Now I want to add a number in the next available cell using assignment.

var index = ????;
a[index] = 4;
console.log(a) // this outputs [1,2,3,4]... more or less...

What does index have to be?

caneno
@caneno
Jul 30 2017 06:01
3?
kumquatfelafel
@kumquatfelafel
Jul 30 2017 06:02
@caneno aye
Now... what's [1,2,3].length?
caneno
@caneno
Jul 30 2017 06:02
3?
kumquatfelafel
@kumquatfelafel
Jul 30 2017 06:02
yep.
caneno
@caneno
Jul 30 2017 06:03
awesome
@kumquatfelafel thanks you are the best :)
CamperBot
@camperbot
Jul 30 2017 06:03
caneno sends brownie points to @kumquatfelafel :sparkles: :thumbsup: :sparkles:
:cookie: 557 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
caneno
@caneno
Jul 30 2017 06:03
just got it
kumquatfelafel
@kumquatfelafel
Jul 30 2017 06:04
@caneno @abhinav-thinktank answer also valid.
caneno
@caneno
Jul 30 2017 06:04
function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var arr1 = arr.sort(function(a, b) {
  return a - b;
});
  for(var i = 0; i < arr1.length; i++){
    if(arr1[i] >= num){
      return arr1.indexOf(arr1[i]);
    }
  }
  return arr1.length;
}

getIndexToIns([2, 5, 10], 15);
that the code I used and it worked
kumquatfelafel
@kumquatfelafel
Jul 30 2017 06:20
@caneno though yeah... to illustrate what @abhinav-thinktank was saying...
function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.push(num); //add num to array
  arr.sort(function(a, b) { //N.B. sort modifies original array, so you don't have to store in new variable.
    return a - b;
  });
  return arr.indexOf(num);
}
If you don't want to modify the original array (otherwise both solutions will), you can also include this line of code at very top...
arr = arr.slice();
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
Adzanny
@zanisis
Jul 30 2017 06:43
guys can be possible to using itenary operations if doing 2 task ? example.
a ? somethingA, somethingB : somethingC
Darth Skywalker
@AdiSkywalker
Jul 30 2017 06:49
@zanisis do it like this
a ? (somethingA, somethingB ): somethingC
You need to wrap comma separated statements/expressions with brackets
Rajat
@rajataudichya
Jul 30 2017 07:03
Please can someone make me understand this ?
https://www.udemy.com/how-to-write-the-ultimate-1-page-marketing-plan/
arey sorry
var arr = [
  [1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
  for (var j=0; j < arr[i].length; j++) {
    console.log(arr[i][j]);
  }
}
korzo
@korzo
Jul 30 2017 07:05
@rajataudichya
arr[0] is [1, 2]
arr[0][0] is 1
Rajat
@rajataudichya
Jul 30 2017 07:06
its too complicated
korzo
@korzo
Jul 30 2017 07:08
@rajataudichya To access element of array we use [] with position inside
so arr[0] is first element of arr array (array indexes are zero based)
Rajat
@rajataudichya
Jul 30 2017 07:08
yes but why is arr[0] is [1,2] and arr [0][0] is 1?
Darth Skywalker
@AdiSkywalker
Jul 30 2017 07:08

@rajataudichya

var arr = [
  [1,2], [3,4], [5,6]
];
for (var i=0; i < arr.length; i++) {
  var innerArray = arr[i];
  for (var j=0; j < arr[i].length; j++) {
    console.log(innerArray[j]);
  }
}

Does this help you understand it better just a little bit ?

korzo
@korzo
Jul 30 2017 07:09
@rajataudichya as first element of arr is also array, we use [] to get first element of arr[0]
Darth Skywalker
@AdiSkywalker
Jul 30 2017 07:09

@rajataudichya

Answer this first

var arr = [1,2,3,4,5];

What will be arr[0] in this case?

kumquatfelafel
@kumquatfelafel
Jul 30 2017 07:15

:point_up:
@rajataudichya It's an array of arrays.

arr[x] tells you "row"
arr[x][y] tells you "column", y, of that row, x.

You can think of it a bit like coordinates.

If I say x = 5, for x-y coordinate plane, that gives you a line of potential points, so I need to give the y value as well if I want to get a specific point on line.

It's not *exactly* the same though, so don't take my example too literally. Just to illustrate concept... array won't have infinite values like a line will.
Rajat
@rajataudichya
Jul 30 2017 07:20
@AdiSkywalker 1 would be the arr
Darth Skywalker
@AdiSkywalker
Jul 30 2017 07:21
@rajataudichya right ... and what would be arr[0] now?
var arr = [ [1,2], 2, 3, 4, 5];
KinderPreet Singh
@kindercappy
Jul 30 2017 08:33
Please checkout my Tic Tac Toe game.
Report any bugs you find. Thanks :grinning:
https://codepen.io/kindercappy/full/qXbVVm/
Abhinav Mishra
@abhinav-m
Jul 30 2017 09:35
@kindercappy looks nice :)
KinderPreet Singh
@kindercappy
Jul 30 2017 09:36
@abhinav-thinktank thanks :)
CamperBot
@camperbot
Jul 30 2017 09:36
kindercappy sends brownie points to @abhinav-thinktank :sparkles: :thumbsup: :sparkles:
:cookie: 437 | @abhinav-thinktank |http://www.freecodecamp.com/abhinav-thinktank
kumquatfelafel
@kumquatfelafel
Jul 30 2017 09:37
@kindercappy If I were going to change anything, maybe provide a way to select single/double player at end of game.
Abhinav Mishra
@abhinav-m
Jul 30 2017 09:38
yes that could be nice
KinderPreet Singh
@kindercappy
Jul 30 2017 09:38
@kumquatfelafel okay... thanks :)
CamperBot
@camperbot
Jul 30 2017 09:38
kindercappy sends brownie points to @kumquatfelafel :sparkles: :thumbsup: :sparkles:
:cookie: 558 | @kumquatfelafel |http://www.freecodecamp.com/kumquatfelafel
Abhinav Mishra
@abhinav-m
Jul 30 2017 09:39
@kindercappy cursor pointer can improve ux a bit, to select which square you want to place your move on
KinderPreet Singh
@kindercappy
Jul 30 2017 09:40
@abhinav-thinktank yes that will be good
a27-suryansh
@a27-suryansh
Jul 30 2017 09:41
Hi i need a small help with PHP can someone please help?
Darth Skywalker
@AdiSkywalker
Jul 30 2017 09:42

@kindercappy Try this pattern

  • select spot in left hand bottom corner (then computer plays)
  • select spot in right hand top corner (then computer plays)
  • select spot in right hand bottom corner (then computer plays)

You always win :D

It works if you mirror image this pattern
nvm.. It seems to have been fixed after refresh
Abhinav Mishra
@abhinav-m
Jul 30 2017 09:45
@AdiSkywalker wanna help me fix some shitty ajax code and react
using htmlhttprequest
xmlhttprequest
KinderPreet Singh
@kindercappy
Jul 30 2017 09:45
@AdiSkywalker ya man. its not unbeatable :P
Abhinav Mishra
@abhinav-m
Jul 30 2017 09:46
const RowData = (props) => <tr className="dataRow">
        <td>{props.content.id}</td>
        <td>{props.content.picture}</td>
        <td>{props.content.name}</td>
        <td>{props.content.points}</td>
</tr>

class TableData extends React.Component {








  constructor() {
    super();
    this.state = {
      allData: [],
      recentData: []
    }
  }
  componentDidMount() {

    const allURL= "https://fcctop100.herokuapp.com/api/fccusers/top/alltime";
    const recentURL ="https://fcctop100.herokuapp.com/api/fccusers/top/recent";
    const  that =this;
  var xHttpReqRecent = new XMLHttpRequest();
  var xHttpReqAll = new XMLHttpRequest();
  xHttpReqRecent.open("GET",recentURL);
  xHttpReqRecent.send();

  xHttpReqAll.open("GET",allURL);
  xHttpReqAll.send();

  xHttpReqRecent.onreadystatechange = function () {
    if(this.readyState == 4 && this.status==200)
      {
      var data = JSON.parse(this.responseText);
     that.setState({recentData:data});
      }

  }


  xHttpReqAll.onreadystatechange = function () {
     if(xHttpReqAll.readyState == 4 && this.status==200)
      {
     var  data = JSON.parse(this.responseText);
     that.setState({allData:data});
      }
  }



  }
  render() {

   return( <table className="dataTable">

     <tbody>
      {this.state.allData.map( (content) => <RowData key={content.id} content={content} />)}
      </tbody>
    </table>)
  }
Darth Skywalker
@AdiSkywalker
Jul 30 2017 09:47
@abhinav-thinktank okay.. let me check
Abhinav Mishra
@abhinav-m
Jul 30 2017 09:47
I have done this @AdiSkywalker However, render () is being called without the request being completed
thus rendering nothing
Darth Skywalker
@AdiSkywalker
Jul 30 2017 09:48
@abhinav-thinktank Yeah... render will be called before request completion (in most cases)
Abhinav Mishra
@abhinav-m
Jul 30 2017 09:48
theres more to the code, but this is the section that i need to fix right now
@AdiSkywalker but then how does using promises ensure that state is changed in a timely manner
won't it be the same?
Darth Skywalker
@AdiSkywalker
Jul 30 2017 09:48
This part is where problem lies
xHttpReqRecent.onreadystatechange = function () {
    if(this.readyState == 4 && this.status==200)
      {
      var data = JSON.parse(this.responseText);
     that.setState({recentData:data});
      }

  }
first this inside you function will be undefined
change it to arrow function.
I don't like that thatpart
Abhinav Mishra
@abhinav-m
Jul 30 2017 09:49
@AdiSkywalker im binding the previous this using that
it is getting updated, i verified that while debugging
but the render is done before that.
Darth Skywalker
@AdiSkywalker
Jul 30 2017 09:49
do you have codepen?
Abhinav Mishra
@abhinav-m
Jul 30 2017 09:50
ill need to post it..
wait a bit
Darth Skywalker
@AdiSkywalker
Jul 30 2017 09:50
If your render happens before this request finishes, you need to use componetDidUpdate hook
@abhinav-thinktank I'll be off for 15 mins.. post your pen here meanwhile. Will take a look when I'm back
anyone here
Muhammad Hasham
@MohammadHasham
Jul 30 2017 09:58
anyone who can help me with react?
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:00
@MohammadHasham might be able to help if its something easy
:D
Stephen James
@sjames1958gm
Jul 30 2017 10:00
@abhinav-thinktank you get a number of rows which implies that the data array has data in it
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:01
@sjames1958gm yea, while debugging, the render was being called with an empty array
@sjames1958gm then the control shifted back to myresponse, and the array was being populated for the state
@sjames1958gm somewhere on stack overflow this is mentioned
render() {
    if (!this.state.page) {
        return <div>Loading...</div>
    }
    return (
        <div>
            <div>{this.state.page.somedata}</div>
        </div>
    )

}
Stephen James
@sjames1958gm
Jul 30 2017 10:02
@abhinav-thinktank You will get one render at least with no data
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:02
@sjames1958gm yea im not getting any error, just no data
Stephen James
@sjames1958gm
Jul 30 2017 10:02
But after the request you should get the data
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:03
@sjames1958gm you mean after my state changes, the component will automatically update it?
sorry , not sure what youre implying
Stephen James
@sjames1958gm
Jul 30 2017 10:03
It should, when you call setState you should get a re-render with the data
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:04
huh.. not happening in my case..
maybe im doing something wrong
Stephen James
@sjames1958gm
Jul 30 2017 10:05
@abhinav-thinktank There is no id in the content - that may be a problem - I put username in your row component
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:05
how can i use setState in fetch api
Stephen James
@sjames1958gm
Jul 30 2017 10:06
{
"username": "sjames1958gm",
"img": "https://avatars2.githubusercontent.com/u/4639625?v=3",
"alltime": 7731,
"recent": 311,
"lastUpdate": "2017-07-14T06:41:32.735Z"
},
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:06
so that it shall wait for some time until the data is fetched to set the state
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:06
@sjames1958gm my god.
thats such an asinine mistake.
Thanks for your help as always!
CamperBot
@camperbot
Jul 30 2017 10:06
abhinav-thinktank sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8195 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Stephen James
@sjames1958gm
Jul 30 2017 10:06
@MohammadHasham Call setState in the callback or promise handler
Pieter Stokkink
@forkerino
Jul 30 2017 10:06
@MohammadHasham fetch returns a promise, no? So you can use setState in the .then.
@sjames1958gm :wave:
Stephen James
@sjames1958gm
Jul 30 2017 10:07
@forkerino Morming - it is still morning there?
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:07
@sjames1958gm so the componentDidUpdate hook isn't needed.
i see.
Pieter Stokkink
@forkerino
Jul 30 2017 10:07
@sjames1958gm just after noon. Good morning to you!
Stephen James
@sjames1958gm
Jul 30 2017 10:07
@abhinav-thinktank They recommend componentDidUpdate for API requests.
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:08
 thirtyDays = () => {
    const API_URL = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent';
    fetch(API_URL).then(function(response){
      return response.json();
    }).then(function(value){
         setTimeout(()=>{
           let names = value;
           this.setState({array:names});
         },3000);
    });
   console.log(this.state.array);
actually it is setting the state before the data is fetched maybe.
the state is undefined.
@sjames1958gm @forkerino @abhinav-thinktank
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:08
@MohammadHasham your setstate seems fine...
@MohammadHasham show how you're rendering
Stephen James
@sjames1958gm
Jul 30 2017 10:09
@MohammadHasham Your .then needs an arrow function to get the correct this
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:09
@sjames1958gm where?
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:09
@MohammadHasham aah, yes.
Pieter Stokkink
@forkerino
Jul 30 2017 10:10
@MohammadHasham the console.log will run before the .then, so don't rely on that.
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:10
wouldn't it throw an error?
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:10
sorry i can't get it.Where is it>
Stephen James
@sjames1958gm
Jul 30 2017 10:10
@MohammadHasham At least the second one.
@MohammadHasham You don't need the setTimeout
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:11
 thirtyDays = () => {
    const API_URL = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent';
    fetch(API_URL).then(function(response){
      return response.json();
    }).then((value)=>{
         setTimeout(()=>{
           let names = value;
           console.log(names);
         },3000);
    });

  };
Is it okay now
Stephen James
@sjames1958gm
Jul 30 2017 10:11
@MohammadHasham }).then((value) => {
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:11
actually i was using it to add a delay between fetching and setting the state
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:11
curious...
@sjames1958gm why isn't it throwing an error
for this.setState()
aah, i read somewhere it swallows errors in react ..
Stephen James
@sjames1958gm
Jul 30 2017 10:12
@abhinav-thinktank Not sure exactly, would assume you would get a setState is not a function
Pieter Stokkink
@forkerino
Jul 30 2017 10:12
@MohammadHasham you do need a .setState in there
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:12
@sjames1958gm yea i got it without using then
@sjames1958gm but i read somewhere then swallows all errors.
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:12
okay i'll try
^
Pieter Stokkink
@forkerino
Jul 30 2017 10:12
@MohammadHasham just no setTimeout
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:13
@forkerino okay i have removed that now
Stephen James
@sjames1958gm
Jul 30 2017 10:13
I have also read that you don't use arrow functions for class functions
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:13
you have to handle them in catchh
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:13
how can i see that is the data actually being set in state
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:13
@MohammadHasham you can debug it on your local system
@MohammadHasham bind the earlier this
@MohammadHasham and use it to setState inside
@MohammadHasham or use an arrow function , so it doesn't get bount
bound*
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:14
@abhinav-thinktank
const API_URL = 'https://fcctop100.herokuapp.com/api/fccusers/top/recent';
    fetch(API_URL).then(function(response){
      return response.json();
    }).then((value)=>{
        this.setState({array:value})
    });
is it okay now?
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:14
is it working? @MohammadHasham
Pieter Stokkink
@forkerino
Jul 30 2017 10:14
@MohammadHasham looks better.
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:14
yeah success!
Pieter Stokkink
@forkerino
Jul 30 2017 10:14
:+1:
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:14
Thanks @sjames1958gm @forkerino @abhinav-thinktank
CamperBot
@camperbot
Jul 30 2017 10:14
mohammadhasham sends brownie points to @sjames1958gm and @forkerino and @abhinav-thinktank :sparkles: :thumbsup: :sparkles:
:cookie: 438 | @abhinav-thinktank |http://www.freecodecamp.com/abhinav-thinktank
:star2: 2894 | @forkerino |http://www.freecodecamp.com/forkerino
:star2: 8196 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:15
@MohammadHasham :+1:
lol, im so glad i was able to get a basic grasp as to what was going on
:D
progress!
Stephen James
@sjames1958gm
Jul 30 2017 10:16
@MohammadHasham Don't use arrow functions as class functions.
And you need to bind this to the function in React - as in
   // put this in your constructor
    this.thirtyDays = this.thirtyDays.bind(this);

// use this not an arrow function
  thirtyDays() {
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:17
@sjames1958gm this is a question
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:17
@sjames1958gm i see.
Stephen James
@sjames1958gm
Jul 30 2017 10:17
no that is a statement :)
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:17
why isn't using function allowed
Muhammad Hasham
@MohammadHasham
Jul 30 2017 10:17
okay thanks i'll do that
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:17
aah, cause it will bind it's own scope?
i mean
```
function abc() {
Stephen James
@sjames1958gm
Jul 30 2017 10:17
@abhinav-thinktank If you want to use this, function() has its own this
Yes it binds its own this
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:18
aah, i see.
Darth Skywalker
@AdiSkywalker
Jul 30 2017 10:18
@abhinav-thinktank Is it solved now?
Stephen James
@sjames1958gm
Jul 30 2017 10:18
@abhinav-thinktank Since you use Http Request you had to use that because you needed
this to point to the http request
Darth Skywalker
@AdiSkywalker
Jul 30 2017 10:18
I checked your pen, it seems to be working
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:18
@AdiSkywalker yeah, it was a silly mistake.
Darth Skywalker
@AdiSkywalker
Jul 30 2017 10:19
What was that ? @abhinav-thinktank
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:19
@AdiSkywalker the object's properties were differently named than the ones in my component :|
which i was getting from the response
Darth Skywalker
@AdiSkywalker
Jul 30 2017 10:19
:laughing:
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:19
:P
@sjames1958gm if i used an arrow function for readyStatechange
@sjames1958gm won't the this work?
Darth Skywalker
@AdiSkywalker
Jul 30 2017 10:20
@abhinav-thinktank It will
Stephen James
@sjames1958gm
Jul 30 2017 10:20
@abhinav-thinktank How will you get to the state/status of the request?
Abhinav Mishra
@abhinav-m
Jul 30 2017 10:21
aah, good point
good thing i studied about scopes and all this before starting react
:D
well, thanks @sjames1958gm @AdiSkywalker , im gonna try and finish this now
CamperBot
@camperbot
Jul 30 2017 10:21
abhinav-thinktank sends brownie points to @sjames1958gm and @adiskywalker :sparkles: :thumbsup: :sparkles:
:cookie: 277 | @adiskywalker |http://www.freecodecamp.com/adiskywalker
:warning: abhinav-thinktank already gave sjames1958gm points
Stephen James
@sjames1958gm
Jul 30 2017 10:22
@abhinav-thinktank That is why I would suggest fetch API rather than xmlHttpRequest
If you are going modern with React go modern with fetch
Darth Skywalker
@AdiSkywalker
Jul 30 2017 10:22
@abhinav-thinktank :+1:
@sjames1958gm You can get status of request by it's name like
xHttpReqRecent.onreadystatechange = () => {
    if(xHttpReqRecent.readyState == 4 && xHttpReqRecent.status==200) {
       var data = JSON.parse(xHttpReqRecent.responseText);
       this.setState({recentData:data});
    }
  }
Stephen James
@sjames1958gm
Jul 30 2017 10:23
@AdiSkywalker Ah, there you go -
I haven't used that API very often
@AdiSkywalker thx
CamperBot
@camperbot
Jul 30 2017 10:24
sjames1958gm sends brownie points to @adiskywalker :sparkles: :thumbsup: :sparkles:
:cookie: 278 | @adiskywalker |http://www.freecodecamp.com/adiskywalker
Darth Skywalker
@AdiSkywalker
Jul 30 2017 10:24
@sjames1958gm :+1:
Datikzz
@Datikzz
Jul 30 2017 10:57
Hi guys, i have numbers in strings(price) like this '4 299$', '14 399$', how i can sort them?
i tried with regex /([0-9])+/g
heroiczero
@heroiczero
Jul 30 2017 10:59
@Datikzz is that like 4*299$?
Datikzz
@Datikzz
Jul 30 2017 10:59
there is space after thousand digit
1 thousand like - 1 000
heroiczero
@heroiczero
Jul 30 2017 10:59
@Datikzz do you want to sort from highest to lowest?
Datikzz
@Datikzz
Jul 30 2017 11:00
whatever, just want to sort
it gives me error when i try to match with pattern
Datikzz
@Datikzz
Jul 30 2017 11:01
just sort()?
heroiczero
@heroiczero
Jul 30 2017 11:02
@Datikzz if you have an array of strings you could try using that
Datikzz
@Datikzz
Jul 30 2017 11:03
array of objects that have strings
korzo
@korzo
Jul 30 2017 11:04
@Datikzz you need custom sort function. convert strings to numbers and compare them
Datikzz
@Datikzz
Jul 30 2017 11:04
stringtify and replace spaces ?
korzo
@korzo
Jul 30 2017 11:05
@Datikzz yes, replace with '' everything but numbers, then parseInt
heroiczero
@heroiczero
Jul 30 2017 11:07
Abhinav Mishra
@abhinav-m
Jul 30 2017 11:16
anyone here worked with sass
and familiar with stuff
Sue
@coding-sue-true
Jul 30 2017 11:26
Hi everyone
Jim Tryon
@jimtryon
Jul 30 2017 11:26
Hey @coding-sue-true
Sue
@coding-sue-true
Jul 30 2017 11:26
I need some help for an assignment in coursera
I currently have this code
Jim Tryon
@jimtryon
Jul 30 2017 11:27
@coding-sue-true Go ahead and paste the code, I’ll see if I can help
Sue
@coding-sue-true
Jul 30 2017 11:29
sorry I'm trying to past it with te backtips
but it's not working
<!DOCTYPE html>
<html> 
<head>
    <title> Matching Game </title>
    <style type="text/css">
        img{
            position: absolute;
        }
        #rightSide{
            left: 500px;
            border-left: 1px solid black;
        }
        div {
            position: absolute;
            width:500px;
            height: 500px;
        }    

        img {

        }

    </style>


</head>
<body>
    <h1> Matching Game </h1>
    <p> Click on the extra smiling face on the left. </p>
    <div id="leftSide">

    </div>
    <div id="rightSide">

    </div>

    <script type="text/javascript">
            var numberOfFaces = 5;
            var theLeftSide = document.getElementById("leftSide");
            var theRightSide = document.getElementById("rightSide");

        function generateFaces(){
            for (i = 0; i < numberOfFaces; ++i) {
                img = document.createElement("img");
                img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
                img.style.top = Math.floor(Math.random() * 400) + "px";
                img.style.left = Math.floor(Math.random() * 400) + "px";
                theLeftSide.appendChild(img);
            }



        }
            generateFaces();

        var leftSideImages = theLeftSide.cloneNode(true);
        leftSideImages.removeChild(leftSideImages.lastChild);
        theRightSide.appendChild(leftSideImages);

        theLeftSide.lastChild.onclick = function nextLevel(event){

            event.stopPropagation();

            numberOfFaces += 5;

            generateFaces();

        };

        var theBody = document.getElementsByTagName("body")[0];

        theBody.onclick = function gameOver() {

        alert("Game Over!");



            theBody.onclick = null;

            theLeftSide.lastChild.onclick = null;


        };


    </script>
</body>

</html>
right, that's my code.. and the left side is working fine
I need it to do the same on the right side but with less one smile... and I don't know how to
@jimtryon thank you Jim :)
CamperBot
@camperbot
Jul 30 2017 11:31
coding-sue-true sends brownie points to @jimtryon :sparkles: :thumbsup: :sparkles:
:cookie: 417 | @jimtryon |http://www.freecodecamp.com/jimtryon
Darth Skywalker
@AdiSkywalker
Jul 30 2017 11:36
@coding-sue-true You got codepen for this?
Sue
@coding-sue-true
Jul 30 2017 11:37
no
GeorgeII
@GeorgeII
Jul 30 2017 11:47
Hello! Here's my question.
$().ready() {
  $(".selector").click(func1);
}
function func1() {
  /*some
  code*/
  function func2() {
  /*some
  code*/
  }
}
will the func2 be executed?
Pieter Stokkink
@forkerino
Jul 30 2017 11:49
@GeorgeII no
Darth Skywalker
@AdiSkywalker
Jul 30 2017 11:49
@GeorgeII If you call it, yes
GeorgeII
@GeorgeII
Jul 30 2017 11:49
or I have to invoke it like:
$().ready() {
  $(".selector").click(func1);
}
function func1() {
  /*some
  code*/
func2();
  function func2() {
  /*some
  code*/
  }
}
Pieter Stokkink
@forkerino
Jul 30 2017 11:49
@GeorgeII yes, you have to call it
GeorgeII
@GeorgeII
Jul 30 2017 11:49
@forkerino @AdiSkywalker ok ty
CamperBot
@camperbot
Jul 30 2017 11:49
georgeii sends brownie points to @forkerino and @adiskywalker :sparkles: :thumbsup: :sparkles:
:cookie: 279 | @adiskywalker |http://www.freecodecamp.com/adiskywalker
:star2: 2895 | @forkerino |http://www.freecodecamp.com/forkerino
Darth Skywalker
@AdiSkywalker
Jul 30 2017 11:49
@GeorgeII :+1:
Sue
@coding-sue-true
Jul 30 2017 11:50
No one able to help me on my code?
Pieter Stokkink
@forkerino
Jul 30 2017 11:53
@coding-sue-true I'm not exactly sure what you want or need to do?
Sue
@coding-sue-true
Jul 30 2017 11:54
well the goal is to create a matching game, where you always have one more smile on the left side than in the right one
with the code I posted, the left side is correct
but I need it to also increase the number of smiles on the right side, but always with one less smile...
Pieter Stokkink
@forkerino
Jul 30 2017 11:55
@coding-sue-true but only when the thing on the leftside is clicked?
Sue
@coding-sue-true
Jul 30 2017 11:55
yes
and if you click on the wrong it shows "game over", but that last part is working
Pieter Stokkink
@forkerino
Jul 30 2017 11:56
ok.
@coding-sue-true I see two options
Sue
@coding-sue-true
Jul 30 2017 11:56
everytime you click on the right smile, the left side has to increase five smiles
Pieter Stokkink
@forkerino
Jul 30 2017 11:57
  1. To do it in the click handler
Datikzz
@Datikzz
Jul 30 2017 11:57
mm, how to get object's value that is in array?
Pieter Stokkink
@forkerino
Jul 30 2017 11:57
But I think they need to have the same pattern right?
Sue
@coding-sue-true
Jul 30 2017 11:57
yes
Pieter Stokkink
@forkerino
Jul 30 2017 11:57
ok
so you need to do it in the generateFaces() function
that's the second way
Darth Skywalker
@AdiSkywalker
Jul 30 2017 11:58
Datikzz
@Datikzz
Jul 30 2017 11:58
array = [{foo: 'blah'}]
tried console.log(array.foo);
result was undefined
Pieter Stokkink
@forkerino
Jul 30 2017 11:58
@Datikzz in objects you don't have =, but :
Darth Skywalker
@AdiSkywalker
Jul 30 2017 11:58
@Datikzz That's a syntax error mate...
Datikzz
@Datikzz
Jul 30 2017 11:58
wait
just mistype here
Darth Skywalker
@AdiSkywalker
Jul 30 2017 11:59
It should be array = [ { foo:'blah' } ]
Pieter Stokkink
@forkerino
Jul 30 2017 11:59
@Datikzz would be array[0].foo
Darth Skywalker
@AdiSkywalker
Jul 30 2017 11:59
And it should be array[0].foo
Datikzz
@Datikzz
Jul 30 2017 11:59
so i should create loop to get all elements?
Darth Skywalker
@AdiSkywalker
Jul 30 2017 11:59
@Datikzz Yes
Sue
@coding-sue-true
Jul 30 2017 12:00
@AdiSkywalker the codepen you sent..
Pieter Stokkink
@forkerino
Jul 30 2017 12:00
@coding-sue-true i.e. the idea is to append the img to both theLeftSide and theRightSide (the latter only if i is not numberOfFaces-1
Sue
@coding-sue-true
Jul 30 2017 12:00
that's the code I paste it
Datikzz
@Datikzz
Jul 30 2017 12:00
k, thank you
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:01
@coding-sue-true I created it with code you shared here
Sue
@coding-sue-true
Jul 30 2017 12:01
@AdiSkywalker thank you
CamperBot
@camperbot
Jul 30 2017 12:01
coding-sue-true sends brownie points to @adiskywalker :sparkles: :thumbsup: :sparkles:
:cookie: 280 | @adiskywalker |http://www.freecodecamp.com/adiskywalker
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:01
Now... What you want to happen in your code?
@coding-sue-true
Sue
@coding-sue-true
Jul 30 2017 12:02
@forkerino okay... the thing is that javascript is very recent to me, and I don't know how to do that..
@AdiSkywalker I need the right side to be like the left, but with one less smile
Pieter Stokkink
@forkerino
Jul 30 2017 12:03
@coding-sue-true well, you can append the same thing you appended to theLeftSide to theRightSide, but surround that append with an if
Sue
@coding-sue-true
Jul 30 2017 12:03
and everytime the person clicks on the right extra smile on the left side, both sides increase 5 smiles
Pieter Stokkink
@forkerino
Jul 30 2017 12:04
@coding-sue-true you might have to calculate the right relative position, not sure about that.
Sue
@coding-sue-true
Jul 30 2017 12:06
@forkerino thanks, will see what I can do
CamperBot
@camperbot
Jul 30 2017 12:06
coding-sue-true sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2896 | @forkerino |http://www.freecodecamp.com/forkerino
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:06

@coding-sue-true Take a look at updated pen

https://codepen.io/AdiSkywalker/pen/QMyQYB?editors=1010

Updated generateFaces function as follows
function generateFaces() {
  for (i = 0; i < numberOfFaces; ++i) {
    img = document.createElement("img");
    img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
    img.style.top = Math.floor(Math.random() * 400) + "px";
    img.style.left = Math.floor(Math.random() * 400) + "px";
    var _img1 = img.cloneNode(true)
    var _img2 = img.cloneNode(true)
    theLeftSide.appendChild(_img1);
    if(i < numberOfFaces-1){
      theRightSide.appendChild(_img2);
    }
  }
}
And removed this part
var leftSideImages = theLeftSide.cloneNode(true);
leftSideImages.removeChild(leftSideImages.lastChild);
theRightSide.appendChild(leftSideImages);
Sue
@coding-sue-true
Jul 30 2017 12:11
@AdiSkywalker that's close to what I need, yes, thank you, but still, there's something missing
CamperBot
@camperbot
Jul 30 2017 12:11
coding-sue-true sends brownie points to @adiskywalker :sparkles: :thumbsup: :sparkles:
:warning: coding-sue-true already gave adiskywalker points
Sue
@coding-sue-true
Jul 30 2017 12:12
everytime I click in the right extra smile, when a new bunch of smiles is created, they have to randomly change it's position
Pieter Stokkink
@forkerino
Jul 30 2017 12:12
you want to clear everything?
Sue
@coding-sue-true
Jul 30 2017 12:12
I believe I have to use .removeChild somewhere, right?
@forkerino yes, I think it has to be removed, and then created again
Pieter Stokkink
@forkerino
Jul 30 2017 12:13
well, that might get cumbersome with many images
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:13
@coding-sue-true That;s becuase you have this numberOfFaces += 5;
Pieter Stokkink
@forkerino
Jul 30 2017 12:13
You might just want to set the innerhtml to empty
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:13
and then you're calling generateFaces
Seid Akhmed Agitaev
@agitaev
Jul 30 2017 12:15
hi campers
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:15
Update your generateFaces to be
function generateFaces() {
  theLeftSide.innerHTML = '';
  theRightSide.innerHTML = '';
  // rest of the code
and comment out that numberOfFaces += 5;
Seid Akhmed Agitaev
@agitaev
Jul 30 2017 12:16
can anybody tell me what's wrong with this solution?

function filteredArray(arr, elem) {
  let newArr = [];
  // change code below this line
  for(let i = 0; i < arr.length; i++) {
    for(let k = 0; k < arr[i].length; k++) {
      if(arr[i][k] !== elem) {
        newArr.push(arr[i]);
      }
    }
  }
  // change code above this line
  return newArr;
}

// change code here to test different cases:
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));
this is the challenge description: We have defined a function, filteredArray, which takes arr, a nested array, and elem as arguments, and returns a new array. elem represents an element that may or may not be present on one or more of the arrays nested within arr. Modify the function, using a for loop, to return a filtered version of the passed array such that any array nested within arr containing elem has been removed.
Sue
@coding-sue-true
Jul 30 2017 12:16
@AdiSkywalker will do that, thank you :)
CamperBot
@camperbot
Jul 30 2017 12:16
coding-sue-true sends brownie points to @adiskywalker :sparkles: :thumbsup: :sparkles:
:warning: coding-sue-true already gave adiskywalker points
Pieter Stokkink
@forkerino
Jul 30 2017 12:17
@dactice looks like you are pushing the subarray multiple times (possibly)
do you have to use for loops?
Seid Akhmed Agitaev
@agitaev
Jul 30 2017 12:18
yes @forkerino
Pieter Stokkink
@forkerino
Jul 30 2017 12:19
@dactice in that case, you'll need some sort of flag to keep track of whether elem has been found and only push after the inner loop if it hasn't.
Seid Akhmed Agitaev
@agitaev
Jul 30 2017 12:20
@forkerino thanks, let me try
CamperBot
@camperbot
Jul 30 2017 12:20
dactice sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2897 | @forkerino |http://www.freecodecamp.com/forkerino
Pieter Stokkink
@forkerino
Jul 30 2017 12:21
:+1:
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:24
You need to assign onclick handler after every time you generateFaces
otherwise the game fails as you create new faces and the original lastChild is lost
Sue
@coding-sue-true
Jul 30 2017 12:26
yes, that's what I was looking at now
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:27
Man! I always thought making game would be such a pain in the ass... But building this as was much fun as playing it :laughing:
Sue
@coding-sue-true
Jul 30 2017 12:30
@AdiSkywalker thank you very much for your help, it is now working, but I had to leave the numberOfFaces += 5; because otherwise it will always have only 5 smiles
CamperBot
@camperbot
Jul 30 2017 12:30
coding-sue-true sends brownie points to @adiskywalker :sparkles: :thumbsup: :sparkles:
:warning: coding-sue-true already gave adiskywalker points
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:32
@coding-sue-true You wanna increase the difficulty level each time by 5 more faces?
add that line back in
it will work fine now
Sue
@coding-sue-true
Jul 30 2017 12:32
yes, it is working !
yaaaay
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:32
Also, I'd recommend you refactor your code as follows to conform to standard development practices
Sue
@coding-sue-true
Jul 30 2017 12:32
thank youuuu
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:32
var numberOfFaces, theLeftSide, theRightSide, theBody;

function generateFaces() {
  theLeftSide.innerHTML = "";
  theRightSide.innerHTML = "";
  for (i = 0; i < numberOfFaces; ++i) {
    var img = document.createElement("img");
    img.src = "http://home.cse.ust.hk/~rossiter/mooc/matching_game/smile.png";
    img.style.top = Math.floor(Math.random() * 400) + "px";
    img.style.left = Math.floor(Math.random() * 400) + "px";
    var _img1 = img.cloneNode(true);
    var _img2 = img.cloneNode(true);
    theLeftSide.appendChild(_img1);
    if (i < numberOfFaces - 1) {
      theRightSide.appendChild(_img2);
    }
    delete img;
  }
  theLeftSide.lastChild.onclick = nextLevel;
}

function nextLevel(event) {
  event.stopPropagation();
  generateFaces();
}

function gameOver() {
  alert("Game Over!");

  theBody.onclick = null;

  theLeftSide.lastChild.onclick = null;
}

function main() {
  numberOfFaces = 5;
  theLeftSide = document.getElementById("leftSide");
  theRightSide = document.getElementById("rightSide");
  theBody = document.getElementsByTagName("body")[0];
  theBody.onclick = gameOver;
  generateFaces();
}

window.onload = main;
Important thing is this window.onload = main;
And then this theLeftSide.lastChild.onclick = nextLevel;
if you don't do this, the nextLevel function will be recreated again and again leading to memory leaks
Sue
@coding-sue-true
Jul 30 2017 12:34
nice! okay will add that and change
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:36
@coding-sue-true lol.. Where did you get idea for this game?
Will it be okay with you if I add it to my showcase on codepen?
I'll change the image if you want
This game is fun as the difficulty increases
Sue
@coding-sue-true
Jul 30 2017 12:37
It's an assignment for a coursera full stack web development
Darth Skywalker
@AdiSkywalker
Jul 30 2017 12:37
I see
Sue
@coding-sue-true
Jul 30 2017 12:37
But I was stuck with this last bit
i didnt understand how to differentiate b/w consonant and clusters ...
Stephen James
@sjames1958gm
Jul 30 2017 13:06
@a7n007
you can use regex, or loop to test the first letters
a7n007
@a7n007
Jul 30 2017 13:08
function translatePigLatin(str) {
 if(str[0]=='c'||str[0]=='p')
  return str.substr(1,str.length-1)+str[0]+"ay";
 if(str[0]=='g')
  return str.substr(2,str.length-1)+str[0]+str[1]+"ay";
else
  return str+"way";

}

translatePigLatin("consonant");
i completed it like this
@sjames1958gm but how what is the condition i am going to use in regex expressions and can you suggest me a source to learn regex
what is the condition i am going to use
Ronique Ricketts
@RoniqueRicketts
Jul 30 2017 13:10
@a7n007 like
RegExp("a|e|i|o|u", "i")
RegExp(/[bcdfghjklmnpqrstvwxz]{2,}/ , "i");
Stephen James
@sjames1958gm
Jul 30 2017 13:10
@a7n007 let con = str.match(/^[^aeiou]+/);
Then con.length will have the consonant cluster size
Oops that is wrong
The first ^ marks the start of the string, the second one inside the [] means not the following values
a7n007
@a7n007
Jul 30 2017 13:13
@sjames1958gm can you suggest me a source to learn regex
Ronique Ricketts
@RoniqueRicketts
Jul 30 2017 13:13
@a7n007 the first expression match vowels and the last one match consonant blends, so it matches any 2 letters.
Stephen James
@sjames1958gm
Jul 30 2017 13:14
@a7n007 https://regexone.com/
Then read MDN pages to see what javascript supports because js doesn't support the full set of qualifiers
a7n007
@a7n007
Jul 30 2017 13:14
@sjames1958gm thanks BTW i want to ask you something about you can i?
CamperBot
@camperbot
Jul 30 2017 13:14
a7n007 sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8197 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Abhinav Mishra
@abhinav-m
Jul 30 2017 13:21
How would i change state on a component by clicking on another
struggling with this
Stephen James
@sjames1958gm
Jul 30 2017 13:24
You can pass the click up to a parent component via a property (assign as a function)
Then that component can change its state and pass that state down to another component as a property
Abhinav Mishra
@abhinav-m
Jul 30 2017 13:27
@sjames1958gm No way to directly invoke update state on a particular component using setState?
what i've got so far
i think ive structured too many components..
Stephen James
@sjames1958gm
Jul 30 2017 13:31
DataSection seems extraneous.
I don't think you want to be calling setState (if it even works) from another component.
That means that the one component knows the state structure of another component.
Datikzz
@Datikzz
Jul 30 2017 13:49

Guys, i have array of objects like this

arr [
{val: '1'}, 
{val: { newval: '2', oldval: '4'}
];

object value can have 1 value or or 2 values(newel/oldval);
how to compare 'val' with 'oldval' ?

Stephen James
@sjames1958gm
Jul 30 2017 13:51
arr[0].val === arr[1].val.oldval
Muhammad Hasham
@MohammadHasham
Jul 30 2017 13:55
Stephen James
@sjames1958gm
Jul 30 2017 13:56
@MohammadHasham :+1:
Muhammad Hasham
@MohammadHasham
Jul 30 2017 13:56
@sjames1958gm Thanks :D
CamperBot
@camperbot
Jul 30 2017 13:56
mohammadhasham sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8198 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Datikzz
@Datikzz
Jul 30 2017 14:04
@sjames1958gm there can be several objects, and i want to sort them
arr [
{val: '1'}, 
{val: { newval: '2', oldval: '4'},
{val: '1'}, 
{val: { newval: '2', oldval: '4'},
{val: '1'}, 
{val: { newval: '2', oldval: '4'},
{val: '1'}, 
{val: { newval: '2', oldval: '4'},
];
Moisés Man
@moigithub
Jul 30 2017 14:05
whats the sort criteria ?
Stephen James
@sjames1958gm
Jul 30 2017 14:06
@Datikzz
You can test the typeof a.val and if string then use the value if not use a.val.oldval
Something like this?
function getVal(a) {
   if (typeof a.val === "string") return a.val;
   return a.val.oldval;
}
arr.sort((a, b) => 
   +getVal(a) - +getVal(b));
Datikzz
@Datikzz
Jul 30 2017 14:28
@moigithub sort arr by val's values,
if val has many values --> sort by oldval, so in result it should sort (val,oldval,val,oldval...) or (1,4,1,4,1,4)
@sjames1958gm it sorts only Oldval with Newval, other values it doesnt sort
Moisés Man
@moigithub
Jul 30 2017 14:33
if u have 1,4,1,4,1,4 after sorted should be 1,1,1,4,4,4 if ascending
Datikzz
@Datikzz
Jul 30 2017 14:34
the problem is i want to extract those values (1,4,1,4)
rn it sorts 1, 2, 4, 1, 2, 4
Moisés Man
@moigithub
Jul 30 2017 14:37
what u mean by extract values?
put some input/output example data
Stephen James
@sjames1958gm
Jul 30 2017 14:42
Not at all clear what you are wanting.
if val has many values, only pick newVal to sort with other Vals
Stephen James
@sjames1958gm
Jul 30 2017 14:47
@Datikzz Your getVal function is wrong - it refers to input.val
Change getVal to use newVal instead of oldVal - you did this
Datikzz
@Datikzz
Jul 30 2017 14:48
changes nothing
Stephen James
@sjames1958gm
Jul 30 2017 14:50
function getVal(a){
  if(typeof a.val === 'string') return a.val.replace(/ /g,"");
  return a.val.newVal.replace(/ /g, "");
}
Your examples above didn't really show the kind of numbers that were stored in the object
Datikzz
@Datikzz
Jul 30 2017 14:53
damn, i forgot that its unformatted string -_-
thank you guys
Stephen James
@sjames1958gm
Jul 30 2017 15:03
@Datikzz :+1:
Thayyeb salim
@Thayyebsalim
Jul 30 2017 15:41
Could you guyss give your comments about my Random quote generator
Stephen James
@sjames1958gm
Jul 30 2017 15:54
@Thayyebsalim Looks good - I like that the quote area does not resize when the quote size changes.
I am not a big fan of the changing background colors, but that is just me.
Pieter Stokkink
@forkerino
Jul 30 2017 15:58
@Thayyebsalim It works. I think you would've learned more if you actually implemented an API call to an external resource for the quotes (they're called API projects for a reason), but it is a good start.
Thayyeb salim
@Thayyebsalim
Jul 30 2017 15:58
Thanks for the comment @sjames1958gm
I had the quote box responsive, but the button kept moving up and down as the div size changes. So I scraped it.
CamperBot
@camperbot
Jul 30 2017 15:58
thayyebsalim sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8199 | @sjames1958gm |http://www.freecodecamp.com/sjames1958gm
Thayyeb salim
@Thayyebsalim
Jul 30 2017 15:58
I thought about the API call but I was weak at arrays so I tried it
besides the coming projects focuses on APIs right?
Pieter Stokkink
@forkerino
Jul 30 2017 16:00
@Thayyebsalim yes, the next few will be impossible to do without, but they're also more complex. It is in my opinion better to practice first with a simple case like a random quote, so you get the hang of it.
Thayyeb salim
@Thayyebsalim
Jul 30 2017 16:00
aaah thanks for the review
Pieter Stokkink
@forkerino
Jul 30 2017 16:00
But go on and see for yourself!
I'm sure you'll learn it soon enough.
Thayyeb salim
@Thayyebsalim
Jul 30 2017 16:00
I did the next two projects too
Pieter Stokkink
@forkerino
Jul 30 2017 16:01
ah ok
Thayyeb salim
@Thayyebsalim
Jul 30 2017 16:01
I had not put it on for review yet
Seid Akhmed Agitaev
@agitaev
Jul 30 2017 16:09

evening world, please somebody tell me what is wrong with this code:


let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};

function countOnline(obj) {
  // change code below this line
  let count = 0;
  for(let user in obj) {
    if(user.online === true) {
      count++;
    }
  }
    return count;
  // change code above this line
}

console.log(countOnline(users));

I have to loop through the object with for...in and console log the number of users whose online property is true

Thayyeb salim
@Thayyebsalim
Jul 30 2017 16:10
thanks @forkerino
CamperBot
@camperbot
Jul 30 2017 16:10
thayyebsalim sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2898 | @forkerino |http://www.freecodecamp.com/forkerino
Muhammad Hasham
@MohammadHasham
Jul 30 2017 16:10
can anyone give me some ideas to build some redux apps to get a better grasp at it.
Pieter Stokkink
@forkerino
Jul 30 2017 16:10
@dactice user will just refer to the names, not the value (objects) associated with the names.
so obj[user].online would be the property.
Seid Akhmed Agitaev
@agitaev
Jul 30 2017 16:13
@forkerino thanks! i got your answer
CamperBot
@camperbot
Jul 30 2017 16:13
dactice sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2899 | @forkerino |http://www.freecodecamp.com/forkerino
Christopher McCormack
@cmccormack
Jul 30 2017 16:24
:wave: good morning
Pieter Stokkink
@forkerino
Jul 30 2017 16:33
@cmccormack :wave:
Christopher McCormack
@cmccormack
Jul 30 2017 16:33
@forkerino hey man!
Pieter Stokkink
@forkerino
Jul 30 2017 16:34
how's it going?
Christopher McCormack
@cmccormack
Jul 30 2017 16:36
Good hoping to finally finish this React Dungeon project today
I've spent like the last 2 months on and off on it
Pieter Stokkink
@forkerino
Jul 30 2017 16:36
@cmccormack I still have to do the Game of Life thingy.
I'm guessing it's not that hard, but I don't have the time at the moment
Christopher McCormack
@cmccormack
Jul 30 2017 16:37
@forkerino that one was pretty fun. the logic was simple so you can spend more time with style
if you don't care about style, you could probably knock it out in one day easy
Pieter Stokkink
@forkerino
Jul 30 2017 16:37
probably
Christopher McCormack
@cmccormack
Jul 30 2017 16:37
haha
do you use React for work?
Pieter Stokkink
@forkerino
Jul 30 2017 16:37
Nope
Angular
but we do use Redux
IsmailHusseinCR
@IsmailHusseinCR
Jul 30 2017 16:38
Hey FCC

function falsybouncer(arr) {
    let filter = arr.filter((trueValues) => {
    return Boolean(trueValues);
  })
  return filter;
}

console.log(falsybouncer([true,false,"","123","kek"]));
Christopher McCormack
@cmccormack
Jul 30 2017 16:38
@IsmailHusseinCR hi
IsmailHusseinCR
@IsmailHusseinCR
Jul 30 2017 16:38
trueValues is a copy of the array right
Pieter Stokkink
@forkerino
Jul 30 2017 16:38
@IsmailHusseinCR no, it is each element in the array in turn
one at a time
IsmailHusseinCR
@IsmailHusseinCR
Jul 30 2017 16:39
so its kinda like if you loop for(i ... < arr.length) and then do arr[i] @forkerino
Christopher McCormack
@cmccormack
Jul 30 2017 16:39
@forkerino I need to start using Redux, I've been reading up on it but haven't implemented it yet. Know if any good cheat sheets for all the different pieces?
Pieter Stokkink
@forkerino
Jul 30 2017 16:39
@cmccormack we might switch over to React at some point, but don't have the capacity at the moment.
@cmccormack the Redux docs are pretty good, actually.
@IsmailHusseinCR yes, kinda
IsmailHusseinCR
@IsmailHusseinCR
Jul 30 2017 16:40
alright thanks @forkerino
CamperBot
@camperbot
Jul 30 2017 16:40
ismailhusseincr sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2900 | @forkerino |http://www.freecodecamp.com/forkerino
Pieter Stokkink
@forkerino
Jul 30 2017 16:40
@cmccormack to understand it on a deep level there's a good course on egghead by the creator
Christopher McCormack
@cmccormack
Jul 30 2017 16:42
I'll have to check it out. It all seems simple enough once you add the different pieces, can't wait to start using it
Thanks @forkerino
CamperBot
@camperbot
Jul 30 2017 16:42
cmccormack sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2901 | @forkerino |http://www.freecodecamp.com/forkerino
Christopher McCormack
@cmccormack
Jul 30 2017 16:43
reading up on Redux actually helped me understand React better too, learning when to use state and when to use properties, what is state, etc...
Pieter Stokkink
@forkerino
Jul 30 2017 16:43
@cmccormack I love Redux. It makes the rest of the code so easy to understand.
Christopher McCormack
@cmccormack
Jul 30 2017 16:46
I really dig React/Redux and how, once you understand it, you can create pretty useful sites so quickly
Kelechi Chinaka
@ke1echi
Jul 30 2017 16:54
i hope i get to that point :smile: @cmccormack @forkerino
Christopher McCormack
@cmccormack
Jul 30 2017 16:57
@kelechy start now! Once you get the hang of React it's awesome! Does have a sharp learning curve though
Pieter Stokkink
@forkerino
Jul 30 2017 16:57
Easier to learn than angular in my experience. :joy:
Moisés Man
@moigithub
Jul 30 2017 17:02
react pretty easy.... its based on components
n there are many ways to create components
const MyComponent = ()=>(<h1>Hello world</h1>)
Abhinav Mishra
@abhinav-m
Jul 30 2017 17:04
I just spent a day on react
the thing with react is initially you pull out your hair learning it..
then you start to love it as you understand it
Christopher McCormack
@cmccormack
Jul 30 2017 17:06
yeah, and it feels less hacky then some other frameworks as well
Abhinav Mishra
@abhinav-m
Jul 30 2017 17:06
i won't know, this is my first framework :D
hope to learn more at some point, but this seems very promising
Javi Ferré
@CurrentDate
Jul 30 2017 17:23
Hi guys i have some little doubt, anyone could help me? I dont know why var cnt is 6 after set the test method to false . https://repl.it/JpHV
Blauelf
@Blauelf
Jul 30 2017 17:27
@CurrentDate Remove g from your regular expression. With g, it keeps track of the position of the last match, and will try to continue after that. You want to test just if there's one match in the whole string, so don't keep that position and remove the g.
Javi Ferré
@CurrentDate
Jul 30 2017 17:29
@Blauelf Thank you :) Yes I pass through that error :S
CamperBot
@camperbot
Jul 30 2017 17:29
currentdate sends brownie points to @blauelf :sparkles: :thumbsup: :sparkles:
:star2: 4547 | @blauelf |http://www.freecodecamp.com/blauelf
Blauelf
@Blauelf
Jul 30 2017 17:31
YW. It's a somewhat common mistake. People tend to not realize what the global flag does, and what it needs to do what it does.
Gbenga Oyetade
@gbengaPS
Jul 30 2017 17:37
Hi everyone. Does anyone here by chance make use of travis-ci?
a7n007
@a7n007
Jul 30 2017 17:50
function booWho(bool) {
 var bol=new Boolean(bool);
  return bol;
}

booWho(null);
i didnt understand this question
can anyone help me
Ruben
@Vivanti
Jul 30 2017 17:54
@a7n007 what's the question?
Pieter Stokkink
@forkerino
Jul 30 2017 18:11
@a7n007 you have to check if bool is either true or false. You can use the Boolean function, but it is not strictly necessary. However new Boolean() creates an object.
so that latter is not the most useful option
a7n007
@a7n007
Jul 30 2017 18:15
can you help me a little more
Pieter Stokkink
@forkerino
Jul 30 2017 18:16
@a7n007 how would you check if bool is either true or false?
Nick Forlivio
@whackdev
Jul 30 2017 18:17
I'm using the below as an express router but everything is defaulting to the / route. Any idea what I'm missing?
const router = require('express').Router();
const urlController = require('./ctrl');

router.get('/:key', (req, res) => {
  res.status(302).redirect(urlController.handleRequest(req.params.key));
});

router.get('/new/:link', (req, res) => {
  res.status(200).json(urlController.newRequest(req.params.link));
});

router.get('/', (req, res) => { 
  res.render('../views/index', (err, html) => {
    if (err) throw err;

    res.status(200).send(html);
  });
});

module.exports = router;
Johnny
@JohnnyBizzel
Jul 30 2017 18:18
@whackdev what happens if you provide a key?
Nick Forlivio
@whackdev
Jul 30 2017 18:18
nothing it goes to the index.html
^ @JohnnyBizzel
@JohnnyBizzel do you want to see the server code?
/**
 * Dependencies
 */
const express = require('express');
const path = require('path');
const Router = require('./api/routes');

/**
 * Create app
 */
export const app = express();


/**
 * View engine setup
 */
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html')

/**
 * Routing
 */
app.use('*', Router)
Johnny
@JohnnyBizzel
Jul 30 2017 18:21
@whackdev that is taking a query string right?
a7n007
@a7n007
Jul 30 2017 18:21
@forkerino is it with if condition
Pieter Stokkink
@forkerino
Jul 30 2017 18:21
@a7n007 yes, that is one of the easiest ways
but you can also do everything in one return statement
Nick Forlivio
@whackdev
Jul 30 2017 18:22
@JohnnyBizzel yeah I am in the early stages of setting up my url shortening microservice so I don't have any actual keys but I have logs statements to see if it contacts the database and the function handler is doing what it's supposed to but they aren't getting triggered just the root landing page
a7n007
@a7n007
Jul 30 2017 18:24
@forkerino can you explain a bit more please
Nick Forlivio
@whackdev
Jul 30 2017 18:24
@JohnnyBizzel all of the code is here but I'm sure I'm missing something simple in the router https://github.com/whackdev/url-shortener
Pieter Stokkink
@forkerino
Jul 30 2017 18:25
@a7n007 well, you have to return true if bool is true or false and false otherwise, so you can use what you learned here to shorten everything to one statement: https://www.freecodecamp.org/challenges/returning-boolean-values-from-functions
gotta go
forkerino @forkerino out
a7n007
@a7n007
Jul 30 2017 18:26

```js
function uniteUnique(...arr) {
var arr1=[];
var c=1;
var arr=arr.reduce(function(a, b) {
return a.concat(b);
});
for(var i=0;i<arr.length;i++)
{
for(var j=i+1;j<arr.length;j++)
{
if(arr[j]!=arr[i])
c=1;
else
{c=0;break;}
}
if(c==1)
arr1.push(arr[i]);
}
return arr1;
}

uniteUnique([1, 3, 2], [1, [5]], [2, [4]]);
``` how to change this code so that it works https://www.freecodecamp.org/challenges/sorted-union this is for deleting duplicates

@forkerino ```js
function booWho(bool)
{
if(Boolean.bool)
return true;
else
return false;
}

booWho(false);
```works for everycase except 2 cases

Moisés Man
@moigithub
Jul 30 2017 18:30
Boolean(bool) maybe ?
a7n007
@a7n007
Jul 30 2017 18:32
@moigithub no i tried
Johnny
@JohnnyBizzel
Jul 30 2017 18:32
@whackdev I have completely forgotten what app.use(*) does. Can you remind me.
Nick Forlivio
@whackdev
Jul 30 2017 18:34
@JohnnyBizzel it sould catch all requests and send them to the router the syntax is app.use(<path>, Handler)
Moisés Man
@moigithub
Jul 30 2017 18:34
on the function call booWho(false); <-- its passing a boolean value.. so u no need to "transform" that value to boolean
just evaluate its value..
if (bool) {....}
@a7n007
Johnny
@JohnnyBizzel
Jul 30 2017 18:36
@whackdev ah ok. So did you do a console.log inside each route?
Nick Forlivio
@whackdev
Jul 30 2017 18:37
@JohnnyBizzel yeah in the controller, but I just went in and commented out the route functions and replaced them with res.send() and the log statments because I need to get this working before I worry about those other functions
@JohnnyBizzel right now I am trying replacing the app.use('*', Router) with the 3 individual routes
@JohnnyBizzel but that seems like double work not DRY code
Johnny
@JohnnyBizzel
Jul 30 2017 18:38
@whackdev I mean in the router.
Nick Forlivio
@whackdev
Jul 30 2017 18:39
@JohnnyBizzel yeah I did that too
@JohnnyBizzel this fixed the /new/:link path but /:key still goes to /
/**
 * Dependencies
 */
const express = require('express');
const path = require('path');
const Router = require('./api/routes');

/**
 * Create app
 */
export const app = express();


/**
 * View engine setup
 */
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html')

/**
 * Routing
 */
app.use('/new/:link', Router)
app.use('/:key', Router)
app.use('/', Router)
Johnny
@JohnnyBizzel
Jul 30 2017 18:45
@whackdev So that should go to Router.handleRequests ?
Nick Forlivio
@whackdev
Jul 30 2017 18:46
@JohnnyBizzel yeah and print out "Connect to DB and redirect to long URL"
Matt Conley
@meatballx
Jul 30 2017 18:47
So I just finished the Spinal Tap Case algorithm and I always like to check and see what the "spoilers" under get help are when I finish a challenge and compare notes, and noticed that basically everyone went an entirely different route than me, using loops and whatnot. This is the solution I came up with, are there any major drawbacks to it that anyone can see?
function spinalCase(str) {
  /* Add a space between letters that are lowercase followed by uppercase, then replace
  any spaces or underscores with a hyphen, then convert to lowercase */
  return str.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/[\s_]/g, "-").toLowerCase();
}

spinalCase('thisIsSpinalTap');
Nick Forlivio
@whackdev
Jul 30 2017 18:47
@JohnnyBizzel the new route is succesfully sending "Respond with JSON obj containing orig & short urls"
a7n007
@a7n007
Jul 30 2017 18:48
function uniteUnique(...arr) {
  var arr1=[];
  var c=1;
  var arr=arr.reduce(function(a, b) {
  return a.concat(b);
});
  for(var i=0;i<arr.length;i++)
    {
      for(var j=i+1;j<arr.length;j++)
        {
          if(arr[j]!=arr[i])
            c=1;
          else
          {c=0;break;}
        }
      if(c==1)
      arr1.push(arr[i]);
    }
  return arr1;
}

uniteUnique([1, 2, 3], [5, 2, 1]);
Johnny
@JohnnyBizzel
Jul 30 2017 18:48
@whackdev did you post the Router code?
a7n007
@a7n007
Jul 30 2017 18:48
my above code isnt giving a sorted list can anyone help
Nick Forlivio
@whackdev
Jul 30 2017 18:50
@JohnnyBizzel
const router = require('express').Router();
const urlController = require('./ctrl');

router.get('/:key', (req, res) => {
  res.send('Redirect to long url')
  // res.status(302).redirect(urlController.handleRequest(req.params.key));
});

router.get('/new/:link', (req, res) => {
  res.send('Respond with JSON obj with short & orig urls');
  // res.status(200).json(urlController.newRequest(req.params.link));
});

router.get('/', (req, res) => { 
  res.render('../views/index', (err, html) => {
    if (err) throw err;

    res.status(200).send(html);
  });
});

module.exports = router;
kumquatfelafel
@kumquatfelafel
Jul 30 2017 18:51
@a7n007 Why would your code give a sorted list? You're pushing elements when they're not equal to next element in concatenated array, not when you find smallest or largest element that isn't part of new array.
Darth Skywalker
@AdiSkywalker
Jul 30 2017 18:52
@whackdev move app.use('/:key', Router) above /new route
and it should work
Moisés Man
@moigithub
Jul 30 2017 18:54
below :point_down:
Nick Forlivio
@whackdev
Jul 30 2017 18:55
@AdiSkywalker the new route still works but that didn't change the key route still goes to /
a7n007
@a7n007
Jul 30 2017 18:57
@kumquatfelafel how to adjust my code so that i get correct answer
Johnny
@JohnnyBizzel
Jul 30 2017 18:58
@whackdev I started learning by following Derek Banas's tutorial. The code is here: https://github.com/JohnnyBizzel/derek-banas-express/blob/master/express.js He doesn't use query strings. Anyway, can you do some test on the key being input to see if it is valid before redirecting?
@whackdev what are you using for keys? Numbers?
Nick Forlivio
@whackdev
Jul 30 2017 18:59
@JohnnyBizzel Thanks I'll try that, yes I was going to use numbers that would be the object ids in the database
CamperBot
@camperbot
Jul 30 2017 18:59
whackdev sends brownie points to @johnnybizzel :sparkles: :thumbsup: :sparkles:
:star2: 1732 | @johnnybizzel |http://www.freecodecamp.com/johnnybizzel
Johnny
@JohnnyBizzel
Jul 30 2017 19:00
@whackdev When I did this challenge I used req.url but did all the work on the /api/ route
Nick Forlivio
@whackdev
Jul 30 2017 19:01
@JohnnyBizzel ok I have to go get the kids some food but when I get back I'll tinker with it some more I appreciate the help
Johnny
@JohnnyBizzel
Jul 30 2017 19:01
@whackdev good luck :+1:
kumquatfelafel
@kumquatfelafel
Jul 30 2017 19:03
@a7n007 I would start by trying to get rid of the elements that are not unique. You don't have to do everything at once. Think of it as a series of individual steps you need to take to solve the problem.
aRtoo
@artoodeeto
Jul 30 2017 19:03
master need help. how can i adjust my cards just to fit 3users?? and if its less then 3 it will center. heres the codepen master. https://codepen.io/artoo/pen/YxPOWP
kumquatfelafel
@kumquatfelafel
Jul 30 2017 19:12
@a7n007 also, you don't actually want to sort them. You just want them in the same order as they were in the original arrays. It's better if you preserve the order. The main thing you want to do... is remove all subsequent duplicates (or not add them in the first place).
a7n007
@a7n007
Jul 30 2017 19:13
i dont understand how
@kumquatfelafel and can you tell me regex to identify '&'
kumquatfelafel
@kumquatfelafel
Jul 30 2017 19:13
@a7n007 Essentially, you only want to keep the first occurrence of a number.
a7n007
@a7n007
Jul 30 2017 19:14
yeah
so if it occured for first time i should allow it to occur again
i will try
kumquatfelafel
@kumquatfelafel
Jul 30 2017 19:15

@a7n007 you should not allow it to occur again.

[1,2,3] and [1, 4, 0] should become [1,2,3, 4, 0]. No second 1.

[2, 7, 4] and [1, 8, 7] becomes [2, 7, 4, 1, 8]. No second 7.
and so on
@a7n007 You mean like /&/g???
kumquatfelafel
@kumquatfelafel
Jul 30 2017 19:26
@meatballx Why replace it with '$1 $2' as opposed to replacing with '$1-$2'?
Eunice Park
@eunicode
Jul 30 2017 19:26

I'd appreciate some help deciphering JavaScript code

var randomNumber = Math.floor(Math.random() * 75);

document.body.style.backgroundImage = "url('https://source.unsplash.com/collection/766896/${getRandomNumber()}')";

So I understand everything except for ${getRandomNumber()}. Is it jquery? Google leads me to template literals

nsonhouse
@nsonhouse
Jul 30 2017 19:28
Hello all.
I need help with an app.get to db.collection.find()
Any takers?
Matt Conley
@meatballx
Jul 30 2017 19:32
@kumquatfelafel What is the difference? Im still brand new to regular expressions and have poured over documentation but it's probably the hardest to memorize I've run in to yet :P
Eunice Park
@eunicode
Jul 30 2017 19:34
Okay, nvm. It's a template literal
Matthew
@mtphil
Jul 30 2017 19:35
@eunipa As far as I know, template literals use ``s though, not “”s.
Eunice Park
@eunicode
Jul 30 2017 19:41
@mtphil Thanks for the insight. It was a typo on my part.
CamperBot
@camperbot
Jul 30 2017 19:41
eunipa sends brownie points to @mtphil :sparkles: :thumbsup: :sparkles:
:cookie: 315 | @mtphil |http://www.freecodecamp.com/mtphil
Ronique Ricketts
@RoniqueRicketts
Jul 30 2017 19:47
omg it worked!! I didn't even know there was a thing as a Fibonacci
function sumFibs(num) {
   var allNumbers = [1];
  var array = [];
  for(var i = 1; i < num; i++){
   if(i === 1){
     allNumbers.push(1);
   }
    else{
     allNumbers.push(allNumbers[allNumbers.length-1] + allNumbers[allNumbers.length-2]);
    }

  }
  allNumbers.forEach(function(a, b, c){
    if(a % 2 !== 0 && a <= num){
      array.push(a);
    } 

  });
  return array.reduce(function(a,b){return a+b},0);
}
sumFibs(4);
Conor Murphy
@cmurphy580
Jul 30 2017 19:51

Need a little help on this beta challenge https://beta.freecodecamp.com/en/challenges/functional-programming/use-the-filter-method-to-extract-data-from-an-array
here is my answer but it doesn't seem to be working

var filteredList = watchList.filter(v => Number(v.imbdRating) >= 8.0)
                            .map(v => ({ title: v.Title, rating: v.imbdRating }));

i'd appreciate any feedback

Matt Conley
@meatballx
Jul 30 2017 19:51
@a7n007 try /[&]/g
a7n007
@a7n007
Jul 30 2017 19:52
``` @meatballx thanks
CamperBot
@camperbot
Jul 30 2017 19:52
a7n007 sends brownie points to @meatballx :sparkles: :thumbsup: :sparkles:
:cookie: 277 | @meatballx |http://www.freecodecamp.com/meatballx
a7n007
@a7n007
Jul 30 2017 19:53
@kumquatfelafel sorry it is working i didnt code it properly
Jahid Bin Kibria
@jahidbinkibria
Jul 30 2017 19:58
i am trying to us unsplash search api
but it said "Auth error: The access token is invalid"
Johnny
@JohnnyBizzel
Jul 30 2017 20:22
P
Matt Smith
@Aakduce
Jul 30 2017 20:29
hey all
i am stuck on Accessing Nested Objects i am not 100% sure how they want me to write the code.
Amit Patel
@AmitP88
Jul 30 2017 20:32
hey guys, quick question: For the Tic Tac Toe project, would it be a bad idea to use a table for the grid? Or should I stick to using divs?
Christopher McCormack
@cmccormack
Jul 30 2017 20:33
@Aakduce they just want you to access the values in an object - use dot or bracket notation depending on whether you know the specific property name or if you instead have a variable or a property name with spaces/special characters
@AmitP88 Tables aren't as responsive as something like a bootstrap grid, but you can use tables any time you want
@AmitP88 probably easier to do it that way anyhow
Amit Patel
@AmitP88
Jul 30 2017 20:35
@cmccormack ah ok. yeah, I read online that tables also have x-browser comp issues. I'll probably stick to using custom divs, just wanted a second opinion. thanks! :)
CamperBot
@camperbot
Jul 30 2017 20:35
amitp88 sends brownie points to @cmccormack :sparkles: :thumbsup: :sparkles:
:star2: 1077 | @cmccormack |http://www.freecodecamp.com/cmccormack
Matt Smith
@Aakduce
Jul 30 2017 20:37
myStorage.car["glove box"].maps; this isnt passing i am not sure how they want me to write it. I know it shouldn't be this var gloveBoxContents = "maps";
Christopher McCormack
@cmccormack
Jul 30 2017 20:38
maps isn't a property, it's the value you want to get back
exclude that from your lookup
and you're missing the inside property of the objects stored in car
Matt Smith
@Aakduce
Jul 30 2017 20:42
car.inside[glove box]; ?
i am more confused now lol i am starting to doubt this will ever make sence
Christopher McCormack
@cmccormack
Jul 30 2017 20:43
var myStorage = {
  "car": {
    "inside": {
      "glove box": "maps",
      "passenger seat": "crumbs"
     },
    "outside": {
      "trunk": "jack"
    }
  }
};
car is a property of myStorage object, inside is a property of the car object, glove box is a property of the inside object
Matt Smith
@Aakduce
Jul 30 2017 20:44
so anthing inside the {} is a object inside the code
Christopher McCormack
@cmccormack
Jul 30 2017 20:44
Just remember that each section that's surrounded by curly braces is an object, and all objects are just property: value pairs
yup
so inside is a property of the car object, but inside's value is another object that has two other properties with their own values
Matt Smith
@Aakduce
Jul 30 2017 20:45
so it's like a drop down file system ?
Christopher McCormack
@cmccormack
Jul 30 2017 20:45
Basically, that's another example of nesting, yes
Files in folders in folders etc... similarly in JS you have values in properties in objects in objects, maybe those objects can be in arrays as well depending on the needs