I have simple task, create todo app in react with 3 pages. 1st page is todos (list of all todos),sec page is page/create. And i want to know wow can I do that. I never try to do something like this. If you can pls help.”
Category: javascript
Category Added in a WPeMatico Campaign
Calculate Height/Depth Of Binary Tree Javascript
I am just a beginner, so if the error is something too obvious, I apologize .
My two questions are:
- What is
this.root
in our school’s provided code; - How can I implement the
.height
method in order to measure the depth of a Tree.
The explanation:
We were provided with this code in the class:
function BinarySearchTree(value) {
this.value = value;
this.right = null;
this.left = null;
}
BinarySearchTree.prototype.add = function(value) {
let newLeaf = new BinarySearchTree(value)
if(value > this.value){
this.right === null? this.right = newLeaf : this.right.add(value)
} else {
this.left === null? this.left = newLeaf : this.left.add(value)
}
};
And we were supposed to write a method to calculate the height/depth of a binary tree. Now, while practicing, I’ve seen something odd. Upon creation of a new node of an empty binary tree, the first node ends up being completely empty, while it proceeds to create a new node on the left side of the first empty one. Well, not empty, but whose value is undefined
. Is this a desired behavior?
let newTree = new BinarySearchTree
>undefined
newTree.add(7)
>undefined
newTree.add(3)
>undefined
newTree.add(5)
>undefined
newTree
>BinarySearchTree {value: undefined, right: null, left: BinarySearchTree}
left: BinarySearchTree {value: 7, right: null, left: BinarySearchTree}
right: null
value: undefined
[[Prototype]]: Object
Now, considering the tests are passing for .add
method, obviously I may be wrong in this situation, since this is the code provided to us by the teacher in the class.
This is the code I keep finding online and the reason I am not getting far with my code for .heigth
method is because I am unable to implement this.root
:
function Node(val){
this.value = val;
this.left = null;
this.right = null;
}
function BinarySearchTree(){
this.root = null;
}
How should I proceed with the .height
method?
If it helps, here are the tests:
describe('Binary Search Tree', function() {
var binarySearchTree;
beforeEach(function() {
binarySearchTree = new BinarySearchTree(5);
});
it('should have methods named "add", "contains", "depthFirstPre", "depthFirstIn", "depthFirstPost", "breadthFirst"', function() {
expect(binarySearchTree.add).to.be.a("function");
});
it('should add values at the correct location in the tree', function(){
binarySearchTree.add(2);
binarySearchTree.add(3);
binarySearchTree.add(7);
binarySearchTree.add(6);
expect(binarySearchTree.left.right.value).to.equal(3);
expect(binarySearchTree.right.left.value).to.equal(6);
});
it('height method should return correct height', function() {
binarySearchTree.left = new BinarySearchTree(3);
binarySearchTree.left.left = new BinarySearchTree(1);
expect(binarySearchTree.height()).to.eql(2);
binarySearchTree.left.left.right = new BinarySearchTree(2);
expect(binarySearchTree.height()).to.eql(3);
binarySearchTree.left.left.left = new BinarySearchTree(0);
expect(binarySearchTree.height()).to.eql(3);
binarySearchTree.right = new BinarySearchTree(8);
expect(binarySearchTree.height()).to.eql(3);
});
}
Again, I apologize for a long question. I was trying to write all the relevant information regarding my problem.
Happy holidays!
is JS command `new Date()` the same across different devices and timezones?
Lets say I have a server running in America and Europe, and I run new Date().getTime()
on both machines at the same time, would they both return sameish timestamp?
or could 1 be drastically different?
What affects that return, is it the time configured on the machine executing it?
implementing function into square calculating formula
im kinda really new to html and programing in general so if someone can help me id be really greatful
how do i implement this code into this formula for calculating area of square
*if (r % 1 != 0 || r < 1) {
p.innerHTML = "<span style='color:#FF0000'>Only whole numbers can be inserted!</span>";
} else {
p.innerHTML = area;
}*
<!DOCTYPE html>
<html>
<body>
<p>Click to start .</p>
<button onclick="myFunction()">Start</button>
<p id="a"></p>
<p id="p"></p>
<p id="v"></p>
<script>
function myFunction() {
var a = prompt("Type a.");
var b = prompt ("Type b.");
var c= prompt ("Type c");
var area= 2*(a*b + a*c + b*c);
document.getElementById("a").innerHTML =
"Area of square:" + area;
}
</script>
</body>
</html>
How to make a function only fire when 3 buttons are clicked in Vanilla Javascript?
I couldn’t figure this out or find anything on this on the web.
Basically how would you write code for this:
I have 3 buttons, and I need to click all of them before the function fires.
I know how to have each button do the same thing, but I want it so I have to click all 3 for it to do anything.
If you could give me any example code of this I can find a way to implement it into my project.
If you need me to elaborate let me know.
Thanks!
JS Object Update + React Reducer
I’m struggling to update all “new” attributes too false. Below is an example object.
const msgdata = {
"1511207758": {
"userid": "1000015977",
"text": "hello",
"new": false,
"subjecttitle": null,
"subjectcontent": null,
"datetime": "2017-11-20T19:55:58.000Z"
},
"1511277428": {
"userid": "1000000000",
"text": "hey hi",
"new": false,
"subjecttitle": null,
"subjectcontent": null,
"datetime": "2017-11-21T15:17:08.000Z"
},
"1640341426": {
"userid": "1000000000",
"text": "hellow how are you?",
"new": false,
"subjecttitle": null,
"subjectcontent": null,
"datetime": "2021-12-24T10:23:45.706Z"
},
"1640342296": {
"userid": "1000000000",
"text": "asdfasdf",
"new": true,
"subjecttitle": null,
"subjectcontent": null,
"datetime": "2021-12-24T10:38:16.089Z"
},
"1640342382": {
"userid": "1000000000",
"text": "fxvfv",
"new": true,
"subjecttitle": null,
"subjectcontent": null,
"datetime": "2021-12-24T10:39:41.910Z"
}
}
when I try the following I mess up the object structure changes to an array but I need to maintain the object/key structure – just change the new value to false.
let newMessages = {}
if (payload.length > 0) {
payload.map((item) => {
if (messagesData && messagesData[item.userid]) {
newMessages = Object.keys(messagesData[item.userid].messages).map((key) => ({ ...newMessages[item.userid].messages[key], new: false }))
}
return true
})
console.dir('newMessages')
console.dir(newMessages)
the return object is a standard array – map does that… eg: 0,1,2 keys…
How can I maintain the object structure and just change the new attr.
thx
MongoError: Found unexpected fields after $each in $addToSet
MongoError: Found unexpected fields after $each in $addToSet
await Profile.updateOne(
{ ref },
{
$addToSet: {
"contact": {
$each: [ "addr" ],
$position: 0,
},
},
}
);
Is there a way to quickly add a class to a pre-existing element in VSCode? (with Emmet Notation)
When you want to create a div with a class already applied, you can just type div.foo
and VSCode will change it to be <div class="foo"></div>
, but what if you want to add a class or id to an already existing element?
E.g you already have a div <div></div>
, but you want to add a class called bar
to it, to make it <div class="bar"></div>
Is there any way you can do this with Emmet notation, VSCode, or some other extension?
How to find the “first” prime number in an array with javascript and, end program in that moment
const array = [4, 16, 8, 3, 22, 5]
function isPrime(array) {
for(let i = 0; i < array.length; i++) {
if (array[i] % 2 === 0) {
return false
} else {
return true
}
}
}
console.log(isPrime(array))
I want find first prime number in array and return me end program
React: How to redirect to new route (different id) from same route?
In react-router,
we cannot push the same route in useHisotry()
and cause a re-render. E.g., if component App is showing on route https://localhost:3000
and I click the button Click Me!
, it won’t cause a re-render:
function App() {
const history = useHistory();
return (
<button onClick={() => {history.push('/')}}> Click Me! </button>
)
}
I want to achieve similar functionality, but I am unsure about the approach or what I am missing.
My current route looks like this: https://localhost:3000/user/1
I want to go to user/2 by clicking a button.
My code looks like the below:
<Route exact path="/user/:userId" component={User} />
function User() {
const history = useHistory();
return (
<button onClick={() => {history.push('/user/2')}}> Click Me! </button>
)
}
The above code changes the route but doesn’t re-render the component. How can I fix this issue?
Thanks
My ReactJS app in Chrome Task Manager CPU is High but Windows Task Manage is low. Why?
I’m using Reactjs to create a dashboard site that has about 15 different data grids that update every 500ms via websockets with a large amount of data virtualized per grid (7k records). Performance seems great on multiple lower / higher end machines (tested 5 different pc’s and 1 mac) and the app also performs well in firefox safari and Edge.
My concern is that when I open Chrome’s task manager it says CPU usage is anywhere from 50 to 120; however, if I look at the windows task manager, CPU usage for chrome is only at 4-5%. It would seem that the values in the chrome task manager don’t correlate to the Windows Task Manager.
On chromes dev site at https://developer.chrome.com/docs/extensions/reference/processes/ it says “The most recent measurement of the process’s CPU usage, expressed as the percentage of a single CPU core used in total, by all of the process’s threads. This gives a value from zero to CpuInfo.numOfProcessors*100, which can exceed 100% in multi-threaded processes. Only available when receiving the object as part of a callback from onUpdated or onUpdatedWithMemory.”
Do I need to worry if chrome says my reactjs app is 50-120 CPU? What is it exactly that the chrome task manager measures in regards to CPU usage and how are these values calculated, I don’t understand the above linked text? Is there a better way to measure true CPU usage of my reactjs app?
Thank you.
How to create React useState hook matching to JSON object
I am trying to create a useState hook matching to this object:
[
{
"id":"",
"name":""
}
]
This is how my code is looking like:
const [ galleries, setGalleries ] = useState([
{
id: "",
name: ""
}
])
setGalleries({...galleries, id: gallery.id, name: gallery.name})
print out an array of numbers containing 1 through 100 ([1,…,100]) and says whether the number is divisible by 4 or 7.Use map or .filter if possible
Please write code that prints out an array of numbers containing 1 through 100 ([1,2,…,100]) and says whether the number is divisible by 4 or 7. Please use .map or .filter if possible
let array = [];
for (let i = 1; i <= 100; i++) {
array.push(i);
}
Authorization Error Error 401: deleted_client The OAuth client was deleted
I am working on a nextjs project and using next auth for my authentication , i keep getting this error once i click on here . on the click of a button , i want it to redirect me to the sign up page , where i click my google accont . then it redirects me back to the page
Authorization Error
Error 401: deleted_client
The OAuth client was deleted.
i dont know what to do to solve it , i just want to sign my users in . I am also using firebase in conjuction with nextjs
How can I get the access of a const inside my function?
How can I grant access to my const to be used inside a function? In this case I want to access my const catName
inside my function fetchListings
. I’m getting this error:
Question Updated:
ReferenceError: catName is not defined
<script context="module">
const fetchListings = async () => {
try {
// get reference to listings collection
const listingsRef = collection(db, 'listings');
// create a query to get all listings
const q = query(
listingsRef,
where('type', '==', catName),
orderBy(timestamp, 'desc'),
limit(10)
);
// execute query
const querySnap = await getDocs(q);
let lists = [];
querySnap.forEach((doc) => {
console.log(doc);
});
} catch (error) {
console.log(error);
}
};
fetchListings();
</script>
<script>
import { page } from '$app/stores';
// export the const catName to the function above
export const catName = $page.params.catName;
</script>
Hi {catName}!