These are chat archives for FreeCodeCamp/HelpJavaScript

9th
Jan 2018
Nick Cleary
@Hijerboa
Jan 09 2018 01:00
Hello all! I am currently working on the Tic Tac Toe challenge, and am having some issues with the AI. I have created a minmax algorithm, which theoretically should work (I used an existing algorithm in C++ I found online as a guide on how to proceed). I have however, run into some issues. When I try to run it on codepen, I get a stack overflow error, and when I try to run it on my local machine, I find that my for loops are repeating more times than they should (which makes absolutely no sense). I'm willing to bet it has to do with the recursion on lines 143 and 161 of my JS code. Would anyone be so kind as to help me resolve this? Any help would be greatly appreciated! :-) Link to codepen: https://codepen.io/hijerboa/pen/BJJyXN?editors=0010
Nick Cleary
@Hijerboa
Jan 09 2018 01:16
@JLuboff @kelechy we were going to be launching this past Christmas (2017) but we were unable to finish in time, so Quincy decided to push it back until he deems it ready. He decided that rather than ship a buggy mess, it was best to wait
Stephen James
@sjames1958gm
Jan 09 2018 01:21
@Hijerboa Line 155 seems incorrect
if (board[i][j] == "j") {
Should that be == "-" ?
Nick Cleary
@Hijerboa
Jan 09 2018 01:22
@sjames1958gm you are correct about that.... but I still get the same error :/
Good catch however :P
After a bit of troubleshooting, it looks like the overflow error does not appear until it runs into an empty part of the board
Stephen James
@sjames1958gm
Jan 09 2018 01:25
@Hijerboa So this is just running the test code at the bottom?
Nick Cleary
@Hijerboa
Jan 09 2018 01:26
@sjames1958gm Yep. Currently none of the onscreen stuff has any effect on the minmax algorithm
Stephen James
@sjames1958gm
Jan 09 2018 01:27
@Hijerboa isMax == false means?
Nick Cleary
@Hijerboa
Jan 09 2018 01:27
@sjames1958gm Whether or not that game is playing as maximizer (ie the computer) or the minimizer's (the human)'s move at the point
its going back and forth between the players
Stephen James
@sjames1958gm
Jan 09 2018 01:29

@Hijerboa There is no reason (in the code) that classType could be "j" and/or "h" - it would make the code cleaner.

if (classType == "js") {
                        board[i][j] = "j";
                    } else if (classType == "html") {
                        board[i][j] = "h";
                    }

this would be just
board[i][j] = classType;

Nick Cleary
@Hijerboa
Jan 09 2018 01:31
@sjames1958gm are you saying that the classtype and the board values should follow the same same naming scheme?
Stephen James
@sjames1958gm
Jan 09 2018 01:31
@Hijerboa I am saying they could and it might simplify the code which would leave less code to be prone to error.
Nick Cleary
@Hijerboa
Jan 09 2018 01:32
@sjames1958gm It would wouldn't it... But that would make too much sense :P
Stephen James
@sjames1958gm
Jan 09 2018 01:34
@Hijerboa :)
Nick Cleary
@Hijerboa
Jan 09 2018 01:34
@sjames1958gm when you did the tictactoe challenge, did you use a minmax or something else?
Stephen James
@sjames1958gm
Jan 09 2018 01:35

@Hijerboa I had a simple strategy

- Take center square if not taken
- else, win if possible
 - else, block if needed
 - otherwise random

It played smart but not perfrect

Nick Cleary
@Hijerboa
Jan 09 2018 01:36
@sjames1958gm was that unbeatable?
I'm pretty sure there are ways to beat that strat
Stephen James
@sjames1958gm
Jan 09 2018 01:36
@Hijerboa No, but I didn't want unbeatable.
Nick Cleary
@Hijerboa
Jan 09 2018 01:36
I legit thought it was supposed to be unbeatable...
Stephen James
@sjames1958gm
Jan 09 2018 01:37
I don't think it has to be, but challenging yourself with minmax is good
Nick Cleary
@Hijerboa
Jan 09 2018 01:37
Dang it... just looked over the requirements... IDK where I got the idea it had to be unbeatable
Stephen James
@sjames1958gm
Jan 09 2018 01:37
@Hijerboa BTW, the check diagonals is not checking the '-'
Nick Cleary
@Hijerboa
Jan 09 2018 01:38
@sjames1958gm what do you mean?
Stephen James
@sjames1958gm
Jan 09 2018 01:39
@Hijerboa For the vertical / horizontal you have board[0][i] != "-" don't you need that for diagonals as well?
maybe use board[1][1] as it is common
Gersho
@Gersho
Jan 09 2018 01:40
i heard it used to be a requirement (being unbeatable)
Nick Cleary
@Hijerboa
Jan 09 2018 01:40
@sjames1958gm I guess that's technically a good idea... I'll add it
@Gersho I think it may be in the video he says it
Stephen James
@sjames1958gm
Jan 09 2018 01:41
@Hijerboa I don't think that is affecting you right now.
I did mine a while back and recall that unbeatable was a bonus challenge
Nick Cleary
@Hijerboa
Jan 09 2018 01:41
@sjames1958gm @Gersho yep... in the video it shows the old page, which has a bonus of being unbeatable
Stephen James
@sjames1958gm
Jan 09 2018 01:43
@Hijerboa Could it be that your i and j are globals and shared with all the various calls to minmax
Change all your for (i to for (var i same with j
Nick Cleary
@Hijerboa
Jan 09 2018 01:44
@sjames1958gm that's my line of thought as well... I'll try that and report back... one sec
@sjames1958gm well.. that resolves one issue: i no longer get the stack overflow error.
doesn't report the correct answer... but that I'll try and troubleshoot myself
@sjames1958gm Thanks so much mate sends internet hugs
CamperBot
@camperbot
Jan 09 2018 01:46
hijerboa sends brownie points to @sjames1958gm :sparkles: :thumbsup: :sparkles:
:star2: 8830 | @sjames1958gm |http://www.freecodecamp.org/sjames1958gm
Stephen James
@sjames1958gm
Jan 09 2018 01:48
@Hijerboa :+1:
Ronique Ricketts
@RoniqueRicketts
Jan 09 2018 02:05
Hi guys question, can I add a mySQL database to glitch?
Pieter Stokkink
@forkerino
Jan 09 2018 08:37
@RoniqueRicketts here are some examples of using a db on glitch: https://glitch.com/storage
Christopher
@bradley1492
Jan 09 2018 12:34

Good afternoon,
after all the help I got here, I can finally grasp a bit more, how counting values in arrays works. I am playing with the following program at the moment:

var str = 'fff';
var chars = str.split("");
var letters_count = {}; 
for(var i = 0; i < chars.length; i++){
  letters_count[chars[i]]++;
}

Why is the execution context of the for-loop only creating one key for 'f' in my letters_count object instead of three?
What is preventing the execution context of creating three key-value pairs?

Markus Kiili
@Masd925
Jan 09 2018 12:38
@bradley1492 The problem is the starting point when there is no property key "f" on the object.
Accessing a non-existent property value results in undefined.
You should first test if the property exists, for example like this:
var str = 'fff';
var chars = str.split("");
var letters_count = {}; 
for(var i = 0; i < chars.length; i++){
  if (!letters_count.hasOwnProperty(chars[i])) letters_count[chars[i]]=0;
  letters_count[chars[i]]++;
}
Christopher
@bradley1492
Jan 09 2018 12:46

@Masd925 Thanks for the answers, is this the same reason for my even simplified version not working out as I am expecting? I would expect testobj to have two 1 key-value pairs instead of one.

var testobj = {}
testobj[1]++;
testobj[1]++;
console.log(testobj);

But it logs only one:

[object Object] {
  1: NaN
}
CamperBot
@camperbot
Jan 09 2018 12:46
bradley1492 sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
:star2: 4643 | @masd925 |http://www.freecodecamp.org/masd925
Kelechi Chinaka
@ke1echi
Jan 09 2018 12:47
@forkerino i once heard you talk about docker... i installed it and ran the quick start but get boot2docker.iso not found locally, pls how do i fix it
Markus Kiili
@Masd925
Jan 09 2018 12:47
@bradley1492 Both lines access the same property with key "1".
testobj[1]++ is the same as testobj[1] = testobj[1] + 1; and that testobj[1] on the right gives undefined and it +1 gives NaN.
Christopher
@bradley1492
Jan 09 2018 12:51
@Masd925 Is the following related thought correct:
By setting testobj[1] to 1, I am setting it to true. I can only set it to true once because true is a boolean and not a quantity? I am not increasing integers here?
Markus Kiili
@Masd925
Jan 09 2018 12:52
@bradley1492 No, the property just either exists or doesn't. It doesn't matter what the value is, a Boolean, a Number etc.
Christopher
@bradley1492
Jan 09 2018 12:54
@Masd925 How would I then go about creating [object Object] { 1: NaN, 1: NaN }?
Markus Kiili
@Masd925
Jan 09 2018 12:56
@bradley1492 That is not possible with an object. The second property just overwrites the first.
Is the idea to produce {f:3} on input of var str = 'fff';?
Pieter Stokkink
@forkerino
Jan 09 2018 13:12
Markus Kiili
@Masd925
Jan 09 2018 13:14
@forkerino Yo.
Pieter Stokkink
@forkerino
Jan 09 2018 13:14
@Masd925 hello
Christopher
@bradley1492
Jan 09 2018 13:31
@Masd925 Ohhhhhhhh now I understand, an Object cannot have the same key twice :)
Markus Kiili
@Masd925
Jan 09 2018 13:31
@bradley1492 :+1:
Christopher
@bradley1492
Jan 09 2018 13:31
@Masd925 thanks :)
CamperBot
@camperbot
Jan 09 2018 13:31
bradley1492 sends brownie points to @masd925 :sparkles: :thumbsup: :sparkles:
api offline
Simon Cordova
@gbsimon87
Jan 09 2018 13:40
@JLuboff long time what's going on man!
Simon Cordova
@gbsimon87
Jan 09 2018 13:46
@Masd925 @forkerino hello as well been some time :)
Markus Kiili
@Masd925
Jan 09 2018 13:47
@gbsimon87 Hi.
Kelechi Chinaka
@ke1echi
Jan 09 2018 13:57
this is head banging @forkerino .. i download boot2docker, opened it and it say i have to burn it to cd
am having a hard time with docker @forkerino :worried:
Simon Cordova
@gbsimon87
Jan 09 2018 14:00
For anyone here that may know which technologies I may need to learn/use I'd appreciate it.
TL/DR - I've got a website which records a game's score (for example, a live basketball game).
Currently, when the game is finished, I'm saving the score to the local storage, so that if need be I can access it in order to view previous game scores.
This does not seem like the most ideal way as dealing with objects in the local storage can be cumbersome.
I was thinking perhaps storing the game results in a database, is this the right approach?
Currently all the functionality is written in Javascript.
Pieter Stokkink
@forkerino
Jan 09 2018 14:11
@kelechy It's not the easiest thing, true. You won't have to burn a cd, but will need to spin up a container where it will run. https://github.com/boot2docker/boot2docker has slightly more info, I cannot really help at the moment
@gbsimon87 :wave:
Simon Cordova
@gbsimon87
Jan 09 2018 14:13
@forkerino thanks buds
CamperBot
@camperbot
Jan 09 2018 14:13
gbsimon87 sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2961 | @forkerino |http://www.freecodecamp.org/forkerino
Pieter Stokkink
@forkerino
Jan 09 2018 14:13
@gbsimon87 If you just want to store it for a single user, you might want to check https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API, otherwise a backend with some database solution is needed.
Simon Cordova
@gbsimon87
Jan 09 2018 14:13
So basically I'd need NodeJS with say MongoDB?
Pieter Stokkink
@forkerino
Jan 09 2018 14:14
That is one way out of many possible ways
:)
But since you already now JS, using Node is probably the easiest to start with
Mongo is not too hard, SQL might also be an option
Simon Cordova
@gbsimon87
Jan 09 2018 14:15
True, that's a good suggestion - I said Mongo because apparently it's the preferred database with NodeJS, for reasons uknown to me - I've yet to dive into backend and databases but I guess I've more than got a reason now!
dinesh
@1532j0004kg
Jan 09 2018 14:27
hi
i need help on storing data's in mongodb collections.
Michael Grienauer
@mgrienauer
Jan 09 2018 14:30
I'm on the exact change challenge and am getting a problem with precision. My code keeps leaving .01 as change and I'mnot srue why

function checkCashRegister(price, cash, cid) {
  //declare change and sum variables
  var change = cash-price;

  //created register object from cid
  var register = cid.reduce(function(acc,curr){
    acc.total += curr[1];
    acc[curr[0]] = curr[1];
    return acc;
  },{"total":0});

  //create list of objects with values of coins/bills
  var denom = [
    { name: 'ONE HUNDRED', val: 100.00},
    { name: 'TWENTY', val: 20.00},
    { name: 'TEN', val: 10.00},
    { name: 'FIVE', val: 5.00},
    { name: 'ONE', val: 1.00},
    { name: 'QUARTER', val: 0.25},
    { name: 'DIME', val: 0.10},
    { name: 'NICKEL', val: 0.05},
    { name: 'PENNY', val: 0.01}
  ];

  //obvious insuff funds
  if (change > register.total){
    return "Insufficient Funds";
  }
  else if (change == register.total){
    return "Closed";
  }

  //logic for what to return
  var change_arr = denom.reduce(function(acc,curr){
    var value = 0;
    //while current denom value is less than change and register has it
    while(change > curr.val && register[curr.name] > 0){
      //update value, change, and register
      value += curr.val;
      change -= curr.val;
      register[curr.name] -= curr.val;
      // Round change to the nearest hundreth deals with precision errors
      change = Math.round(change * 100) / 100;

    }
    //after while loop, push value to acc array if value >0
    if (value > 0){
      acc.push([curr.name, value]);
    }
    return acc;
  },[]);

  if (change_arr.length < 1 || change > 0) {
    return "Insufficient Funds";
  }

  return change_arr;

}



checkCashRegister(19.50, 20.00, [["PENNY", 1.01], ["NICKEL", 2.05], ["DIME", 3.10], ["QUARTER", 4.25], ["ONE", 90.00], ["FIVE", 55.00], ["TEN", 20.00], ["TWENTY", 60.00], ["ONE HUNDRED", 100.00]]);
Pieter Stokkink
@forkerino
Jan 09 2018 14:30
@gbsimon87 Mongo is just one of the options available.
Michael Grienauer
@mgrienauer
Jan 09 2018 14:31
and it's driving me crazy cuz im so close lol
Pieter Stokkink
@forkerino
Jan 09 2018 14:31
But I'm sure it will work fine for this use case @gbsimon87
dinesh
@1532j0004kg
Jan 09 2018 14:32
hi can u help me to store data on backendmongo
Pieter Stokkink
@forkerino
Jan 09 2018 14:32
@mgrienauer I multiplied everything with 100 and then before returning divided everything again.
@1532j0004kg do you have a more specific question? Or maybe some code to show?
dinesh
@1532j0004kg
Jan 09 2018 14:34
yes sure.
Michael Grienauer
@mgrienauer
Jan 09 2018 14:34
@forkerino do you mean in my while loop, or for the register object?
dinesh
@1532j0004kg
Jan 09 2018 14:34
when i try to post things in background and retrieve back is actually working.
Pieter Stokkink
@forkerino
Jan 09 2018 14:35
@mgrienauer I did all the calculations in cents, so I didn't have any floating point numbers in my code right up to the moment I'm returning what needs to be returned.
dinesh
@1532j0004kg
Jan 09 2018 14:35
but the values are not stored in the mongo collection.
Pieter Stokkink
@forkerino
Jan 09 2018 14:36
@1532j0004kg ok, can you show us the code where you are saving it to the collection?
dinesh
@1532j0004kg
Jan 09 2018 14:37
const express = require('express');
const router = express.Router();
const cricketModel = require('../model/score');

router.get('/api/maxi',function(req,res){
  res.send({"type" : "get"});
});

router.post('/api/maxi/',function(req,res){
  console.log("2");
  cricketModel(req.body).save().then(function(data){
   res.send(data);
  console.log(data);
}).catch(err => console.error(err) && res.status(400).send(err));
});

router.delete('/api/maxi/:id',function(req,res){
  res.send({"type" : "delete"});
});

router.put('/api/maxi/:id',function(req,res){
  res.send({"type" : "update"});
});

module.exports = router;
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:38
@1532j0004kg please also post code for ../model/score
Pieter Stokkink
@forkerino
Jan 09 2018 14:38
yes
dinesh
@1532j0004kg
Jan 09 2018 14:39
const mongoose = require('mongoose');
const schema = mongoose.Schema;

const scoreBoard = new schema(
{
  player :  String,

  score :  Number
}
);

const cricketModel = mongoose.model("score",scoreBoard);

module.exports = cricketModel ;
Simon Cordova
@gbsimon87
Jan 09 2018 14:40
@forkerino
I've stumbled upon localForage, any thoughts?
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:40

@1532j0004kg

This part

router.post('/api/maxi/', function(req, res) {
  console.log('2');
  cricketModel(req.body)
    .save()
    .then(function(data) {
      res.send(data);
      console.log(data);
    })
    .catch(err => console.error(err) && res.status(400).send(err));
});

should be

router.post('/api/maxi/', function(req, res) {
  console.log('2');
  const cricket = new cricketModel(req.body);
  cricket
    .save()
    .then(function(data) {
      res.send(data);
      console.log(data);
    })
    .catch(err => console.error(err) && res.status(400).send(err));
});
Pieter Stokkink
@forkerino
Jan 09 2018 14:43
@1532j0004kg yeah, you're missing the new keyword
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:43
@forkerino The code he had shared previously is how this is done in older versions of mongoose
Pieter Stokkink
@forkerino
Jan 09 2018 14:43
@gbsimon87 can be a good option too, we're using it at work for storing part of our application state, so we won't need to request it again and again.
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:43
probably, most of the tutorials online are severely outdated
Simon Cordova
@gbsimon87
Jan 09 2018 14:44
@forkerino
Hmm, interesting, the API also states you can create different instances of it, do you ever do this in practice?
dinesh
@1532j0004kg
Jan 09 2018 14:44
how to view the collections on command line?
Pieter Stokkink
@forkerino
Jan 09 2018 14:44
@SweetCodingInc is it? Did not know that.
@gbsimon87 we don't, because it is a well-encapsulated use case with only one type of data in it.
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:45
@1532j0004kg show collections?
dinesh
@1532j0004kg
Jan 09 2018 14:45
ok i will try
from where i want to type that code?
i mean from wich file or folder
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:46
@1532j0004kg you just asked command line
doesn't matter
as long your mongod is running, open new terminal/cmd
type in mongo
dinesh
@1532j0004kg
Jan 09 2018 14:47
ok
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:47
which will connect to your mongod server
Simon Cordova
@gbsimon87
Jan 09 2018 14:47
@forkerino
Right on...so the concept is the same as the DOM's localStorage API, however it can take in more than just strings basically?
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:47
then do show dbs
then do user <your database name>
then do show collections
dinesh
@1532j0004kg
Jan 09 2018 14:47
from wich directory?
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:48
where is your mongo installed?
never mind
open command prompt at any location
dinesh
@1532j0004kg
Jan 09 2018 14:48
C:\database_mongo\mongodb-win32-i386-3.2.18-4-g752daa3\bin
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:48
and type mongo
dinesh
@1532j0004kg
Jan 09 2018 14:48
from thihs?
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:48
do you see some error like unrecognised command etc?
dinesh
@1532j0004kg
Jan 09 2018 14:49
yes
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:49
is your mongo server running?
dinesh
@1532j0004kg
Jan 09 2018 14:49
1 new connection is open.
actually running
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:50
okay
then just open new command prompt
at any location
and type mongo
see if you get connected to the running server
dinesh
@1532j0004kg
Jan 09 2018 14:50
'mongo' is not recognized as an internal or external command, operable program or batch file.
msg when i typed and enter mongo in cmd
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:51
right
then open command prompt at this location C:\database_mongo\mongodb-win32-i386-3.2.18-4-g752daa3\bin
dinesh
@1532j0004kg
Jan 09 2018 14:52
ok
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:52
do you know how to modify PATHenvironment variable?
dinesh
@1532j0004kg
Jan 09 2018 14:53
no
i running the mongo using mongod --storageEngine=mmapv1 --dbpath "C:\database_mongo\mongodb-win32-i386-3.2.18-4-g752daa3\bin command
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:53
follow this

i running the mongo using mongod --storageEngine=mmapv1 --dbpath "C:\database_mongo\mongodb-win32-i386-3.2.18-4-g752daa3\bin command

Oh dear!!

dinesh
@1532j0004kg
Jan 09 2018 14:54
my lap is 32 bit os
Sweet Coding :)
@SweetCodingInc
Jan 09 2018 14:54
never EVER create databases in the installation directory
dinesh
@1532j0004kg
Jan 09 2018 14:55
i dont know anything .some on told me to use this command to run the mongo
Pieter Stokkink
@forkerino
Jan 09 2018 14:59
@gbsimon87 yeah, basically
dinesh
@1532j0004kg
Jan 09 2018 15:09
@SweetCodingInc what i need to do?
dinesh
@1532j0004kg
Jan 09 2018 15:16
> show dbs gomaxi 0.078GB goninja 0.078GB local 0.078GB score 0.078GB
Zulfan Hameed
@zlfnhmd
Jan 09 2018 15:46
Hello can someone please tell why the html generated by append function does not stay. I mean it run properly but the generated html blinks when the code is run
Matej BoĆĄnjak
@mbosnjak01
Jan 09 2018 15:46
post code
Zulfan Hameed
@zlfnhmd
Jan 09 2018 15:49
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var count=0;
            $('#commentForm').submit(function(event) {
                count++;
                $('#countContainer').append('Total comments:'+ count);
                $('#commentsContainer').append('<div style="background-color:green">'+$(newCommentText).val()+'</div>');
            });
        });
    </script>
    <style type="text/css">
    #newCommentContainer {
        /border-color: black;
        border-style: solid;
        border-width: 1px;
        margin: 4% 24% 1% 24%;
        padding: 1% 1% 1% 1%;
    }

    #commentsContainer {
        border-color: black;
        border-style: solid;
        border-width: 1px;
        margin: 0% 24% 1% 24%;
        padding: 0% 1% 1% 1%;

    }

    #countContainer {
        text-align: left;
    }

    #newCommentAuthor {
        margin-bottom: 5px;
    }
    </style>
    <title></title>
</head>
<body>
    <div class="commentWidgetContainer">
        <div id="newCommentContainer">
            <form id="commentForm">
                  <input id="newCommentAuthor" type="text" name="name" placeholder="Name" autofocus><br>
                  <textarea id="newCommentText" rows="4" cols="50" name="comment-box" placeholder="Enter your comment here"></textarea><br>
                  <input type="submit" value="Submit">
            </form>
        </div>
        <div id="commentsContainer">
            <div id="countContainer"></div>
        </div>
    </div>
</body>
</html>
Hello can someone please tell why the html generated by append function does not stay. I mean it run properly but the generated html blinks when the code is run
Kaz Baig
@kbaig
Jan 09 2018 15:59
@zlfnhmd it's on submission of a form. By default, when you submit a form, your page reloads. To prevent this, add this as the first line in the callback passed to the submit method you're calling
event.preventDefault();
Zulfan Hameed
@zlfnhmd
Jan 09 2018 16:01
Wow that worked
Thanks a ton @kbaig
CamperBot
@camperbot
Jan 09 2018 16:01
zlfnhmd sends brownie points to @kbaig :sparkles: :thumbsup: :sparkles:
:cookie: 494 | @kbaig |http://www.freecodecamp.org/kbaig
Jason Luboff
@JLuboff
Jan 09 2018 16:27
:wave:
texirv0203
@texirv0203
Jan 09 2018 17:17
hi,
  • using the below example, I am trying to implement appDyanmics in my code.
    https://github.com/derrekyoung/appd-sampleapp-angular2
  • but for some reason its not going inside constructor code constructor(public appRoutes:Router) {
  • I kept debugger and saw in the if statement still it didnt go inside.
  • can you tell me how to fix it.
  • providing my code below
import { ModuleWithProviders, NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { Router, Event, NavigationStart, NavigationEnd } from '@angular/router';
import { Base } from './components/base/base';

import { LoadingsWithOverlaps } from './components/Loading/Loadings-with-overlaps';
import { AiringFOXInfoPopup } from './components/Loading/airing-FOXinfo-popup';

import { Listings } from './components/listings/listings';

import { ScoringsMain } from './components/Scorings/ScoringsMain';
import { ScoringFOXTBA } from './components/Scorings/ScoringFOXTBA';
e';

const appRoutes: Routes = [
    {
        path: '',
        redirectTo: 'jumping',
        pathMatch: 'full'
    },

    {
        path: 'FlyingManagement',
        component: FlyingsHeader,
        children: [
            { path: '', redirectTo: 'FlyingSearch', pathMatch: 'full' },
            { path: 'FlyingSearch', component: FlyingSearch },
            {
                path: 'FlyingMain/:id', component: FlyingMain,
                children: [
                    { path: '', redirectTo: 'Base', component: FlyingCreateFill, pathMatch: 'full' },
                    { path: 'FlyingCreateFill', component: FlyingCreateFill, canDeactivate: [CanDeactivateGuard] },

                ]

            }
        ]

    },
    {
        path: 'Playing',
        component: Development

    },


];


export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);
//export class AppRoutingModule { }
declare var ADRUM: any;


@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule],
  providers: []
})

export class AppRoutingModule {

   vpView: any;

//   // Subscribe to the Router URL changes.
  constructor(public appRoutes:Router) {
      console.log("appDyanmics-sample-constructor");
      this.appRoutes.events.subscribe((event:Event) => {
              if (event instanceof NavigationEnd) {
                console.debug('NavigationEnd: '+event.url);

                this.vpView.markViewChangeEnd();
                this.vpView.markViewDOMLoaded();
                this.vpView.markXhrRequestsCompleted();
                this.vpView.markViewResourcesLoaded();
                this.vpView.end();
                ADRUM.Scoring(this.vpView);

              } else if (event instanceof NavigationStart) {
                console.debug('NavigationStart: '+event.url);

                this.vpView = new ADRUM.events.VPageView();
                this.vpView.start();
                this.vpView.markViewChangeStart();
              }
          });
  }
}
Kelechi Chinaka
@ke1echi
Jan 09 2018 17:48
i did it @forkerino
this is a pain :smile: @forkerino
Ghost
@ghost~56ef2a8b85d51f252ab9dec9
Jan 09 2018 18:11
Hey everyone, does someone know React & Redux well here?
Kaz Baig
@kbaig
Jan 09 2018 18:12
@thomlom should post the question so someone can get to it if they are available
Ghost
@ghost~56ef2a8b85d51f252ab9dec9
Jan 09 2018 18:17
I'm building a web app with React & Redux. And for every Container component, I have to write these 2 functions mapStateToProps and mapDispatchToProps and to import the same functions as well (connect and bindActionCreators). Is it OK to write a higher order component that represent a container component to get rid of that duplicated code?
My actual function is the following :
import React, {Component} from 'react';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';

export default function container(WrappedComponent, stateToKeep, actions) {
    class Container extends Component {
        render() {
            return <WrappedComponent {...this.props}/>
        }
    }

    const mapStateToProps = (state) => {
        let stateToPassToComponent = {};
        if (stateToKeep) {
            stateToKeep.forEach(substate => {
                stateToPassToComponent[substate] = state[substate];
            });
        }
        return stateToPassToComponent;
    };

    const mapDispatchToProps = dispatch => {
        if (actions) {
            return bindActionCreators(actions, dispatch);
        } else {
            return {};
        }
    };

    Container = connect(mapStateToProps, mapDispatchToProps)(Container)

    return Container;
}
Kaz Baig
@kbaig
Jan 09 2018 18:24
@thomlom Do you have to create multiple stores? Not sure why you would have to do that
Ronique Ricketts
@RoniqueRicketts
Jan 09 2018 18:42
@forkerino thanks
CamperBot
@camperbot
Jan 09 2018 18:42
roniquericketts sends brownie points to @forkerino :sparkles: :thumbsup: :sparkles:
:star2: 2962 | @forkerino |http://www.freecodecamp.org/forkerino
Ghost
@ghost~56ef2a8b85d51f252ab9dec9
Jan 09 2018 18:44

@kbaig No I don't have to create multiple stores. It's just that I keep defining the same functions across my container components.

for example for my Signin Component, I have to write it like that :

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';

// Action imports

class Signin extends Component {
    /* Code in signin component */
}

const mapStateToProps = (state) => ({
   // Which part of the state I want to pass to my component
})

const mapDispatchToProps =  (dispatch) => {
   return bindActionCreators({ /* My actions */}, dispatch)
}

Signin = connect(mapStateToProps, mapDispatchToProps)(Signin)

export default Signin;

And with my container function, I write my component that way :

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Link} from 'react-router-dom';

// Action imports

class Signin extends Component {
    /* Code in signin component */
}

export default container(Signin, [/* which part of the state I want to pass to my component */], { /* my actions */}) ;

which is shorter.

But I'm not sure if this is actually a good idea

Kaz Baig
@kbaig
Jan 09 2018 18:47
@thomlom I would say you should generally have a parent component for your react app anyways
And that parent should be connected to Redux
Ghost
@ghost~56ef2a8b85d51f252ab9dec9
Jan 09 2018 18:47
@kbaig What do you mean?
Kaz Baig
@kbaig
Jan 09 2018 18:48
You're only calling ReactDOM.render once right? So it renders one component that all your other components are children of
Pieter Stokkink
@forkerino
Jan 09 2018 18:50
@thomlom connect is a higher order component that pretty much does what you are doing here, I don't see the added value of the extra layer.
Ghost
@ghost~56ef2a8b85d51f252ab9dec9
Jan 09 2018 18:52
@forkerino You've got a point
Kaz Baig
@kbaig
Jan 09 2018 18:53
^ That's what I'm trying to get at. You just wrap your highest level parent component with the component resulting from connect. Not sure why you have to do it multiple times
I could be misunderstanding
Ghost
@ghost~56ef2a8b85d51f252ab9dec9
Jan 09 2018 18:56
@kbaig I didn't understand what you mean at first. But I get it, I feel dumb :sweat_smile:
Kaz Baig
@kbaig
Jan 09 2018 18:57
@thomlom glad it makes sense now :)
Ghost
@ghost~56ef2a8b85d51f252ab9dec9
Jan 09 2018 19:00
I have another question, does it worth it to learn TypeScript to build a full stack app with React?
Kaz Baig
@kbaig
Jan 09 2018 19:02
I personally wouldn't use TS with React, that's mostly an Angular thing
A small subset of the community enjoys using it but yeah
There are alternative tools for typing control
Ghost
@ghost~56ef2a8b85d51f252ab9dec9
Jan 09 2018 19:12
@kbaig Ok, thanks for your response :)
CamperBot
@camperbot
Jan 09 2018 19:12
thomlom sends brownie points to @kbaig :sparkles: :thumbsup: :sparkles:
:cookie: 498 | @kbaig |http://www.freecodecamp.org/kbaig
Brad
@bradtaniguchi
Jan 09 2018 19:32
@thomlom as someone who uses typescript for angular, Id say only even consider it if your project is going to be very complex, and or you will be working with a large group of people. If your by yourself, or in a very small team on a basic app, its more or less redundant.
Zulfan Hameed
@zlfnhmd
Jan 09 2018 19:37
<!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var count=0;
            $('#commentForm').submit(function(event) {
                event.preventDefault();
                count++;
                $('#countContainer p').append(count);
                $('#commentsContainer').append('<div id="comment'+count+'" style="background-color: #f1f1f1; padding: 5px 5px 5px 5px; margin-bottom: 5px; border-color: grey;border-style: solid;border-width: 1px; overflow: auto;"><div>'+$(newCommentAuthor).val()+' commented:</div><div>'+$(newCommentText).val()+'</div><hr><p class="replyArea"></p><textarea class="replyText" rows="4" cols="50" name="reply-box" placeholder="Enter your reply here"></textarea><br><button class="replyButton">Reply</button></div>');
                $('.replyButton').click(function(event) {
                    $(this).siblings('.replyArea').prepend($(this).siblings('.replyText').val()+'<br>');
                });
            });

        });
    </script>
    <style type="text/css">
    #newCommentContainer {
        border-color: black;
        border-style: solid;
        border-width: 1px;
        margin: 4% 24% 1% 24%;
        padding: 1% 1% 1% 1%;
    }

    #commentsContainer {
        border-color: black;border-style: solid;border-width: 1px;
        margin: 0% 24% 1% 24%;
        padding: 0% 1% 1% 1%;

    }

    #countContainer {
        text-align: left;
    }

    #newCommentAuthor {
        margin-bottom: 5px;
    }
    </style>
    <title></title>
</head>
<body>
    <div class="commentWidgetContainer">
        <div id="newCommentContainer">
            <form id="commentForm">
                  <input id="newCommentAuthor" type="text" name="name" placeholder="Name" autofocus><br>
                  <textarea id="newCommentText" rows="4" cols="50" name="comment-box" placeholder="Enter your comment here"></textarea><br>
                  <input type="submit" value="Submit">
            </form>
        </div>
        <div id="commentsContainer">
            <div id="countContainer"><p>Total comments: </p></div>
        </div>
    </div>
</body>
</html>

Guys so there is bug which causes extra replies in the previous comment when new comments are added. the replies get multiplied from top to bottom.
So when i make the first comment and make replies to it, it works perfectly.
When I make the second comment, the replies in second comment work perfectly but when i reply to the first comment the reply is added twice and son on

Please help me out

Ghost
@ghost~56ef2a8b85d51f252ab9dec9
Jan 09 2018 19:40
@bradtaniguchi I don't doubt about that
@zlfnhmd Do you have a Codepen link or something like that to make it easier to debug?
Zulfan Hameed
@zlfnhmd
Jan 09 2018 19:41
@thomlom will post it in a bit
Zulfan Hameed
@zlfnhmd
Jan 09 2018 19:57

https://codepen.io/zlfnhmd/pen/BJYPwZ

Guys so there is bug which causes extra replies in the previous comment when new comments are added. the replies get multiplied from top to bottom.
So when i make the first comment and make replies to it, it works perfectly.
When I make the second comment, the replies in second comment work perfectly but when i reply to the first comment the reply is added twice and son on

Please help me out

Stephen James
@sjames1958gm
Jan 09 2018 20:44
@zlfnhmd Because your '.replyButton' selector when you add the second comment selects both the first and second comment
so you have two click handlers on the first one which causes double processing.
@zlfnhmd You need to make unique classes for selection for each comment or you will run into trouble
Jason Luboff
@JLuboff
Jan 09 2018 20:45
@sjames1958gm Are you familar with C# or at least working with SQL queries in .NET?
Stephen James
@sjames1958gm
Jan 09 2018 20:45
@zlfnhmd Well I see now that you are calling unbind
@JLuboff Sorry no
Jason Luboff
@JLuboff
Jan 09 2018 20:46
@sjames1958gm No worries :D
Kaz Baig
@kbaig
Jan 09 2018 20:47
@JLuboff I could help if it's a SQL question, though I suspect it isn't
Zulfan Hameed
@zlfnhmd
Jan 09 2018 20:48

@zlfnhmd Well I see now that you are calling unbind

Yes that solved the issue, but i would like to know how you would have solved it

Jason Luboff
@JLuboff
Jan 09 2018 20:49

@kbaig I'm building sql queries in my program by using parameters for example

"select * from tblWhatever where ID = @id"

Then you set the parameteer later on. All my queries are good except for one I'm having some trouble getting the query to return the proper result. I'm passing in a list to my method then using foreach to create the query and then another foreach to add the parameters but something is getting goofed up lol

Stephen James
@sjames1958gm
Jan 09 2018 20:49
@zlfnhmd I probably would have made unique selectors (class based on index or something) and selected the elements that way.
Zulfan Hameed
@zlfnhmd
Jan 09 2018 20:52
@sjames1958gm That was my initial idea, I have made unique id's for each comment. But I could not figure out a way to select the unique comment and apply append to it with one function
Stephen James
@sjames1958gm
Jan 09 2018 20:58
@zlfnhmd I think your use of $(this).sibling is not a bad choice. There might be some efficiency issues if you ended up with a lot of buttons that you were
removing and adding click handlers to.
Kaz Baig
@kbaig
Jan 09 2018 21:00
@sjames1958gm would you say that the awkwardness in this situation is a weakness of jquery or just the way it's been implemented here? I'm not sure if there's a much better way to do it
To me, this is evidence for why we've moved on from it
Zulfan Hameed
@zlfnhmd
Jan 09 2018 21:00

@zlfnhmd Well I see now that you are calling unbind

@kbaig suggested that

Stephen James
@sjames1958gm
Jan 09 2018 21:02
@kbaig I don't think it is a jquery weakness. I think the building of the html is one big string does not leave you with access to the element that you could attach the
handler to. I think you could make a function that implements a "component" type model and is able to add the handler to the specific element (button).
This I think is where React and other frameworks for creating components shine
Kaz Baig
@kbaig
Jan 09 2018 21:02
If this is for an interview, it's good to know the shortcomings of the implementation or perhaps the library in this case @zlfnhmd
Yeah as soon as I saw the html string I thought about how else I would do it and a naive component implementation was the first thing to come to mind
Stephen James
@sjames1958gm
Jan 09 2018 21:03
@kbaig naive or native :)
Kaz Baig
@kbaig
Jan 09 2018 21:03
naive
Stephen James
@sjames1958gm
Jan 09 2018 21:03
Ah, I see what you mean - yes.
I did some work for my brother a year or so ago using python to build the html, I look back on that an cringe
Kaz Baig
@kbaig
Jan 09 2018 21:05
oh man I can only imagine
But this is HelpJavaScript, we don't talk about that other thing over here ;)
Zulfan Hameed
@zlfnhmd
Jan 09 2018 21:05
Thank you @kbaig @sjames1958gm
CamperBot
@camperbot
Jan 09 2018 21:05
zlfnhmd sends brownie points to @kbaig and @sjames1958gm :sparkles: :thumbsup: :sparkles:
api offline
:star2: 8833 | @sjames1958gm |http://www.freecodecamp.org/sjames1958gm
Zulfan Hameed
@zlfnhmd
Jan 09 2018 21:14
@sjames1958gm @kbaig Is there a way that i can select comments dynamically?