I'm currently working on some practice for JavaScript and am really confused about what I am to do here. Any help would be appreciated!
Define a method named orderOfAppearance() that takes the name of a role as an argument and returns that role's order of appearance. If the role is not found, the method returns 0. Ex: orderOfAppearance("Elizabeth Swann") returns 3. Hint: A method may access the object's properties using the keyword this. Ex: this.title accesses the object's title property.
// Code will be tested with different roles and movies
let movie = {
title: "Pirates of the Caribbean: At World's End",
director: "Gore Verbinski",
composer: "Hans Zimmer",
roles: [ // Roles are stored in order of appearance
"Jack Sparrow",
"Will Turner",
"Elizabeth Swann",
"Hector Barbossa"
],
orderOfAppearance: function(role) {
/* Your solution goes here */
if (!(role in this.roles)) {
return 0;
}
return this.role;
/*Solution ends here */
}
};
A doubly linked list has 2 links. Let's use common sense for a moment instead of blind deferral to whatever you think your TA said: "Doubly linked list" obviously implies "2 links", otherwise that'd be an extremely silly name, no?
So, there must be 2 links. You seem to be under the impression that 'you must not have a pointer to the tail' implies 'there must be only one link'. That can't be right, what with 'doubly linked list' and all.
The right answer is presumably that each node has 2 links, but these links aren't 'head and tail', but 'next' and 'previous'.
For a ringed list (where moving forward from the last element gets you back to the first, and moving backwards from the first element gets you to the last), the last node's "next" link goes back to the first node, and conversely, the first node's "previous" link goes to the last (so it points at the same thing a hypothetical 'tail' would point to).
However, that'd be only true for the first node in your linked list structure (that would be the only node for which 'prev' points at the tail).
Your TA either means 'have next/prev links, not next/tail links' as per above, or has no idea what they are talking about. Let's give em the benefit of the doubt ;) – as it's homework I'll leave the actual writing of the data structure, using a definition of DoublyLinkedNode<T> that includes fields DoublyLinkedNode<T> next, prev;, as an exercise for you.
What I was looking for was to refer to the last use first.getPrev(), since its a circle the last is before the first.
I have the same question. This is found in a zybooks online textbook. The textbook's portion of JavaScript is horrible!! It explains little about what we need to do to solve the questions posed. I have been so frustrated and had to look to online sources to try to solve the problems in the book. Was there a solution to this question?
Define a method named orderOfAppearance() that takes the name of a role as an argument and returns that role's order of appearance. If the role is not found, the method returns 0. Ex: orderOfAppearance("Elizabeth Swann") returns 3. Hint: A method may access the object's properties using the keyword this. Ex: this.title accesses the object's title property.
// Code will be tested with different roles and movies
let movie = {
title: "Pirates of the Caribbean: At World's End",
director: "Gore Verbinski",
composer: "Hans Zimmer",
roles: [ // Roles are stored in order of appearance
"Jack Sparrow",
"Will Turner",
"Elizabeth Swann",
"Hector Barbossa"
],
orderOfAppearance: function(role) {
\\your solution goes here
return this.roles;
}
};
I entered return this.roles; but everything else in the code came from the computer. the answer comes up wrong and says:
Testing orderOfAppearance("Elizabeth Swann")
Yours and expected differ. See highlights below.
Yours
Jack Sparrow,Will Turner,Elizabeth Swann,Hector Barbossa
Expected
3
I also entered:
return this.roles[3]
but that gives Hector Barbossa. I don't know what to do!
If the role is not found, the method returns 0. Ex: orderOfAppearance("Elizabeth Swann") returns 3.
You can use .indexOf() to get the index of the role passed to the orderOfAppearance() method and then add 1 to it. .indexOf() will return -1 if the role is not found and it will become 0 after adding 1.
let movie = {
title: "Pirates of the Caribbean: At World's End",
director: 'Gore Verbinski',
composer: 'Hans Zimmer',
roles: ['Jack Sparrow', 'Will Turner', 'Elizabeth Swann', 'Hector Barbossa'],
orderOfAppearance: function(role) {
return this.roles.indexOf(role) + 1
},
}
console.log(movie.orderOfAppearance('Jack Sparrow'))
console.log(movie.orderOfAppearance('Will Turner'))
console.log(movie.orderOfAppearance('Elizabeth Swann'))
console.log(movie.orderOfAppearance('Hector Barbossa'))
console.log(movie.orderOfAppearance('Something that does not exist in roles'))
Related
I have an array of objects that is basically like this.
const characters = [
{
id: 1
name: batman
biography: {
born-in: gotham
good-or-bad: good
}
stats: {
strength: 85
speed: 90
intelligence: 95
}
}
{
id: 2
name: superman
biography: {
born-in: krypton
good-or-bad: good
}
stats: {
strength: 90
speed: 85
intelligence: 80
}
}
{
id: 3
name: joker
biography: {
born-in: gotham
good-or-bad: bad
}
stats: {
strength: 70
speed: 95
intelligence: 100
}
}
]
Then, after mapping and displaying the objects in my page, I add a button that allows the user to mark the character as a favorite. The user can only add up to 6 favorites.
const [favorites, setFavorites = useState([]);
const addFavorite = () => {
favorites.length === 6 ?
console.log("favorites' list is full!") :
setFavorites(favorites.concat(character))
}
{characters.map((character)=>{
const {props} = character;
return (
<div>{props}</div>
<button onClick={addFavorite}>add to favorites</button>
);
})}
Now, what I want to do (and I don't know how to, after many attempts)
preventing the user to add the same character twice to favorites. (I have tried with favorites.contains(character)? or favorites.contains({character})? but it didn't work.)
if the character is already a favorite, make the button change to a button that removes the favorite instead (changing both the function and the button text.)(I have no idea how to do this).
Make an average score of all favorites' each stat. (For example, with your chosen favorites your average speed is xxx and your average strength is xxx).
Last, but not least, favorites list must have up to 3 good characters and 3 bad characters. So, if the good or bad characters in the favorites' list are already 3, user cannot choose another good or bad character as favorite. I also don't know how to proceed with this one.
I'm working in a school project and I found my way through most of it, but I realise I still have things to learn, mostly about object props and how to access to them. Thank you. If anything is not clear, please say so and I will add the required data.
So, since you've already figured it out yourself, here is the detailed explanation.
find is a function ( or what fancy developers like to say a higher order function ) available for javascript arrays that accepts a function which must return a boolean value i.e., either true or false.
---Quick detour---
A function which must return a boolean value is called a predicate, and this is exactly what's available in the IDE hints if you hover over find
---Detour end---
It accepts multiple parameters, with only the predicate being mandatory, and the rest are optional, i'm skipping all the optional ones, so that's your homework, read the docs or the articles at the end of this answer.
As you can read in the hint itself, it will call the predicate, once for each element in the array, until it can find one which will return true & return the value of the element, undefined otherwise.
Which means : that the first parameter in the predicate is going to be your object and the same predicate will be executed on it for all the elements.
Now observe your solution carefully:
find( savedChar => savedChar.id === character.id )
savedChar is one of the objects in the array, and it needs to be compared with the character object, and id which is the short form of identity will always find it accurately.
Finally, quick answers to your problems.
Use find to see if the character is already available, if yes, simply don't add it in your collection.
This will require you to change your render logic, find if the object is in the favorites and render it differently.
just like find, there is a method called reduce, why don't you give it a shot? but that might be a little difficult, so you can use a simple for loop instead.
find(savedChar => savedChar["good-or-bad"]) <- what would this result? figure it out.
And for more reading material :
https://medium.com/swlh/array-helper-methods-in-es6-28fc5e5a5dc9
same but more detailed :
https://codeburst.io/learn-and-understand-es6-helpers-easily-d41401184487
I'm quite new to web dev and am giving my very first steps in AJAX functions and HTTP requests.
I only know vanilla JS, CSS and HTML. I also know very very little about regExps so would really appreciate if answers could respect this.
I'm developing a simple quiz game where I fetch Q&As from opentdb. The data is saved in an array of questions with the following format (notice the ' on correct-answer):
[..., {
category: "Entertainment: Film",
type: "multiple",
difficulty: "medium",
question: "What Queen song plays during the final fight scene of the film "Hardcore Henry"?",
correct_answer: "Don't Stop Me Now",
incorrect_answers: [
"Brighton Rock",
"Another Bites the Dust",
"We Will Rock You"
]
}, ...]
After having successfully fetched the data the first thing I do is to put all the correct answers in an array which I use later to compare with the user's selected answer. My array of correct answers, in this example would be something like (again notice the '):
[... ,"Don't Stop Me Now", ...]
When I render the questions and answers to the DOM, by creating the necessary elements and using innerHTML everything shows up well on the browser (i.e. instead of ' I get the actual '.
However, later, when I'm collecting the user's selected answer with:
const selectedAnswer = event.currentTarget.innerHTML
I get "Don't Stop Me Now" and when I compare this with my array of correct answers, I get something like:
"Don't Stop Me Now" === "Don't Stop Me Now"
which returns false when, in fact should be true because is the correct answer...
How do I solve this?
Well ' is a HTML Entity. So I create a new element, then set its innerHTML property to the text with the HTML entity then compare it's innerText with the user's input.
const text = "Don't Stop Me Now";
const checkAnswer = (correct, input) => Object.assign(document.createElement('span'), { innerHTML: correct }).innerText == input;
console.log(checkAnswer(text, "Don't Stop Me Now"));
' is HTML Entity code for '. so if this only what you concern, you could try to map that array first and replace/convert that HTML Entity code into character, like this:
[... ,"Don't Stop Me Now", ...].map(item => item.replace(/'/g, "'"));
You could try using backticks instead of the HTML code for '.
[... ,`Don't Stop Me Now`, ...]
I am trying to check If a field exists in a sub-document of an array and if it does, it will only provide those documents in the callback. But every time I log the callback document it gives me all values in my array instead of ones based on the query.
I am following this tutorial
And the only difference is I am using the findOne function instead of find function but it still gives me back all values. I tried using find and it does the same thing.
I am also using the same collection style as the example in the link above.
Example
In the image above you can see in the image above I have a document with a uid field and a contacts array. What I am trying to do is first select a document based on the inputted uid. Then after selecting that document then I want to display the values from the contacts array where contacts.uid field exists. So from the image above only values that would be displayed is contacts[0] and contacts[3] because contacts1 doesn't have a uid field.
Contact.contactModel.findOne({$and: [
{uid: self.uid},
{contacts: {
$elemMatch: {
uid: {
$exists: true,
$ne: undefined,
}
}
}}
]}
You problems come from a misconception about data modeling in MongoDB, not uncommon for developers coming from other DBMS. Let me illustrate this with the example of how data modeling works with an RDBMS vs MongoDB (and a lot of the other NoSQL databases as well).
With an RDBMS, you identify your entities and their properties. Next, you identify the relations, normalize the data model and bang your had against the wall for a few to get the UPPER LEFT ABOVE AND BEYOND JOIN™ that will answer the questions arising from use case A. Then, you pretty much do the same for use case B.
With MongoDB, you would turn this upside down. Looking at your use cases, you would try to find out what information you need to answer the questions arising from the use case and then model your data so that those questions can get answered in the most efficient way.
Let us stick with your example of a contacts database. A few assumptions to be made here:
Each user can have an arbitrary number of contacts.
Each contact and each user need to be uniquely identified by something other than a name, because names can change and whatnot.
Redundancy is not a bad thing.
With the first assumption, embedding contacts into a user document is out of question, since there is a document size limit. Regarding our second assumption: the uid field becomes not redundant, but simply useless, as there already is the _id field uniquely identifying the data set in question.
The use cases
Let us look at some use cases, which are simplified for the sake of the example, but it will give you the picture.
Given a user, I want to find a single contact.
Given a user, I want to find all of his contacts.
Given a user, I want to find the details of his contact "John Doe"
Given a contact, I want to edit it.
Given a contact, I want to delete it.
The data models
User
{
"_id": new ObjectId(),
"name": new String(),
"whatever": {}
}
Contact
{
"_id": new ObjectId(),
"contactOf": ObjectId(),
"name": new String(),
"phone": new String()
}
Obviously, contactOf refers to an ObjectId which must exist in the User collection.
The implementations
Given a user, I want to find a single contact.
If I have the user object, I have it's _id, and the query for a single contact becomes as easy as
db.contacts.findOne({"contactOf":self._id})
Given a user, I want to find all of his contacts.
Equally easy:
db.contacts.find({"contactOf":self._id})
Given a user, I want to find the details of his contact "John Doe"
db.contacts.find({"contactOf":self._id,"name":"John Doe"})
Now we have the contact one way or the other, including his/her/undecided/choose not to say _id, we can easily edit/delete it:
Given a contact, I want to edit it.
db.contacts.update({"_id":contact._id},{$set:{"name":"John F Doe"}})
I trust that by now you get an idea on how to delete John from the contacts of our user.
Notes
Indices
With your data model, you would have needed to add additional indices for the uid fields - which serves no purpose, as we found out. Furthermore, _id is indexed by default, so we make good use of this index. An additional index should be done on the contact collection, however:
db.contact.ensureIndex({"contactOf":1,"name":1})
Normalization
Not done here at all. The reasons for this are manifold, but the most important is that while John Doe might have only have the mobile number of "Mallory H Ousefriend", his wife Jane Doe might also have the email address "janes_naughty_boy#censored.com" - which at least Mallory surely would not want to pop up in John's contact list. So even if we had identity of a contact, you most likely would not want to reflect that.
Conclusion
With a little bit of data remodeling, we reduced the number of additional indices we need to 1, made the queries much simpler and circumvented the BSON document size limit. As for the performance, I guess we are talking of at least one order of magnitude.
In the tutorial you mentioned above, they pass 2 parameters to the method, one for filter and one for projection but you just passed one, that's the difference. You can change your query to be like this:
Contact.contactModel.findOne(
{uid: self.uid},
{contacts: {
$elemMatch: {
uid: {
$exists: true,
$ne: undefined,
}
}
}}
)
The agg framework makes filtering for existence of a field a little tricky. I believe the OP wants all docs where a field exists in an array of subdocs and then to return ONLY those subdocs where the field exists. The following should do the trick:
var inputtedUID = "0"; // doesn't matter
db.foo.aggregate(
[
// This $match finds the docs with our input UID:
{$match: {"uid": inputtedUID }}
// ... and the $addFields/$filter will strip out those entries in contacts where contacts.uid does NOT exist. We wish we could use {cond: {$zz.name: {$exists:true} }} but
// we cannot use $exists here so we need the convoluted $ifNull treatment. Note we
// overwrite the original contacts with the filtered contacts:
,{$addFields: {contacts: {$filter: {
input: "$contacts",
as: "zz",
cond: {$ne: [ {$ifNull:["$$zz.uid",null]}, null]}
}}
}}
,{$limit:1} // just get 1 like findOne()
]);
show(c);
{
"_id" : 0,
"uid" : 0,
"contacts" : [
{
"uid" : "buzz",
"n" : 1
},
{
"uid" : "dave",
"n" : 2
}
]
}
Long story short, I'm making a real estate agent chatbot and I just implemented a filter allowing the user to search within a range of numbers (e.g. at least one bedroom, under $2500). In order to do this, I made an entity_range composite entity composed of the range type (e.g. at most, exactly) and the entity itself (unit-currency for price, plus some custom entities like the number of bedrooms). Prior to creating entity_range, the entities themselves worked fine. But now, it seems as though the entity part of entity_range is undefined. See a sample of my code below:
function get_count(req, res) {
console.log("price: " + req.queryResult.parameters["entity_range"]["unit-currency"])
var price, beds, baths, num_filter_funct
if(req.queryResult.parameters["entity_range"]["unit-currency"] != undefined) {
price = req.queryResult.parameters["entity_range"]
console.log("price: " + price)
} else {
console.log("could not find parameter")
}
Before creating entity_range, my code looked exactly the same, except without ["entity_range"] between parameters and ["unit-currency"]. Anyway, this code logs:
price: undefined
could not find parameter
after the input "How many for $2500," with the following diagnostic info:
...
"queryResult": {
"queryText": "how many for $2500",
"parameters": {
"entity_range": [
{
"unit-currency": {
"amount": 2500,
"currency": "USD"
}
}
]
}...
So the entity "unit-currency" is recognized by Dialogflow, but not by my program. entity_range does allow users to not specify a range, so that's not the issue:
see screenshot here.
I would greatly appreciate any advice you have to offer!
That JSON shows entity_range being an array instead of an object. an object.
parameters.entity_range[0][“unit-currency”] should work. Note the [0]. You’ll also want to add some checks before this to make sure enitiy_range exists and it’s length is > 0.
And this part is just a guess but perhaps you mistakenly clicked the “Is List” box for this parameter in dialogflow? I’m checking it would probably make it be an object instead of an array and your existing code would work.
I cant find an efficient solution for my query. Here is what I'd like to do.
I have a collection called "releases"
I have a collection called "tracks"
"releases" has the field "releaseDate", which is filled for every "releases" document.
I now would like to have the corresponding releaseDate of "releases" in every "tracks" document under db.tracks.releases.releaseDate
(db.tracks.releases exists already, but without the releaseDate).
To find the corresponding releaseDate, "releases" and "tracks" both have an ICPN number:
db.releases.icpn
db.tracks.releases.icpn
Those can be compared to find the correct releaseDate for every track.
To summarize it:
I need to go through every track, look at the ICPN, search for the release with the same ICPN und copy the releaseDate from the release to the track.
I could only make it work like this:
db.releases.find().forEach(function(doc) {
db.tracks.update(
{ "releases.0.ICPN" : doc.ICPN},
{
$set: { "releases.0.releaseDate": doc.releaseDate},
$currentDate: {"lastModified": true}
},
{ multi: true}
)
})
That worked for my test DB, but it is ultra inefficient to go through every track for every single release.
Do you have any hints to get me on the right track?
Kind regards,
Alex
Currently that query only finds docs where the first element in releases is ICPN
You want to query without an absolute index like:
{ "releases.ICPN" : doc.ICPN}
and update with the positional operator so it updates the one it found to match:
$set: { "releases.$.releaseDate": doc.releaseDate},
Well, the query partially works now, but it stops after editing 1700 tracks (of 160000), although I set multi to true and the condition is true for all other tracks/releases (I checked some unmodified tracks manually if ICPNs match).