Common search algorithms? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 days ago.
Improve this question
Let us say we have the following JavaScript array:
const books = [
{
title: "The Great Gatsby",
description: "A novel about the decadence of the Roaring Twenties and the American Dream"
},
{
title: "To Kill a Mockingbird",
description: "A classic novel about racial injustice and growing up in the South"
},
{
title: "1984",
description: "A dystopian novel about a totalitarian government that controls every aspect of its citizens' lives"
}
];
Now I want to filter the books according to the user query. The code then looks like this:
function validateQuery(string, query) {
}
books.filter(book => validateQuery(book.title, "Gatsby great"));
Let us say we are looking for the book The Great Gatsby
All of these queries should return true when being passed to the validateQuery function:
Gatsby great
The great
Gre th
The grea gatsby *
Which means that:
the query is case insensitive
multiple whitespaces at the start and end of the query and inbetween the words are not a problem
the order of the words does not matter
the words do not have to be right next to each other, so it is like multiple words
What could the body of the validateQuery function look like?
I thought of using RegExp to solve the problem, but maybe there is an even simpler solution which does not need RegEx. Maybe there is also a common algorithm out there to solve this problem, even though I did not find anything on Google.

Related

adding an object in an Array in javascript trough code? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
My teacher made an array in my javascript file that i am not allowed to change.
I am supposed to add new objects to it trough code without touching that array.
This is what my array looks like:
const words = [{
dutch: "vork",
english: "Fork",
dutchDescription: "Iets waarmee je eet dat doorgaans vier tanden heeft.",
englishDescription: "Something you eat with that usually has four tines.",
isknown: false
},
{
dutch: "mes",
english: "knife",
dutchDescription: "Bestek dat snijdt.",
englishDescription: "Cutlery that cuts.",
isknown: false
},
{
dutch: "lepel",
english: "spoon",
dutchDescription: "Bestek waarmee je soep eet.",
englishDescription: "Cutlery you use to eat soup.",
isknown: false
}
];
I tried to make it like this:
function addCustomWord(object) {
const words2 = [{
dutch: "testDutch",
english: "testEnglish",
dutchDescription: "dutchDiscriptionTest",
englishDescription: "englishDiscriptionTest",
isknown: false
}]
words.push(words2);
}
That clearly doesn't work and i am having a hard time trying to find anything that actualy works. I have been trying very different solutions for hours and i can't find anything that works.
Could someone help me with my problem?
Remove the square brackets from words2 because words two is the element you need to add

Want number value to change to string in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I'm working on a monopoly game in javascript. I am fairly new to javascript so please forgive if I don't state things in a logical way. Anyways, I have a position player counter which tracks the space each player is at( there are 40 spaces total within the game ) . I also have a counter which counts a dice roll and resets every turn ( 1 to 6 ) .Right now the position player counter is just a number from 1 to 40 and obviously this is no good for the user experience and I want this number to represent the name of the space ( park place, marvin gardens, or whatever the name of the space happens to be ) .
I think I have the right idea of the player location being linked to a number between 1 to 40 because logically that makes the most sense to me, but I want to convert this counter number to the name of the space within the game. Obviously this should also update after every dice roll. I'm including a picture to show what I mean. The thing I'm trying to change is in the upper right. monopoly game
Once again, I'm sorry that my descriptions may be crude. I have only been studying web design and javascript for a few months and this is my first beginner project and my first post here. Thanks everyone.
You can use an array to map the numbers to the names:
var spaceNames = ["Space 1", "Space 2", "Space 3", "Space 4"];
Then you can get the names like this:
spaceNames[spaceNumber - 1];
The -1 is needed because Javascript arrays are 0 based, meaning that the first item in an array is 0. You can read more about that here.

highlighting specific words in a string of text using different colors [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am getting one string and one array of strings from api, for example as below. (These string and array is dynamic)
samplestring = "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth.";
samplearray = dance,love,sing (The count is also dynamic)
I want to highlight the strings from samplearray if they are in samplestring,
Something Like
is there anyway to achieve this by css or js?
I saw this question but I can not use this because my string is dynamic. I saw this question also, but I am not sure how to implement.
You can search every words and replace the source string with the tags.
Set it using innerHTML
var samplestring = "You've gotta dance like there's nobody watching, Love like you'll never be hurt, Sing like there's nobody listening, And live like it's heaven on earth.";
const samplearray = ["dance","Love","Sing"]
samplearray.forEach(str => {
samplestring = samplestring.replaceAll(str, `<span>${str}</span>`)
})
root.innerHTML = samplestring
span {
color: red
}
<div id="root"></div>

What will be a correct data structure for questionnaire [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I am trying to develop a questionnaire where questions are dependent on answers, What will be correct UI data structure to hold the questions and questionnaire flow?
Sorry if this unclear, Would like to eliminate some parts of the UI based on the answers, so i need some kind of data structure in Java script so I can dynamically modify the html based on the answers, so the question is how to bring the data as json to the page, and how to hold it in JS and eliminate some parts of the UI based on the json and answers.
1 What is your name?_______
2 Did you ever code in java?___Y/N____
3 <Question should appear only if answer is yes> How many years? ____
4 <Question should appear only if answer is no> Did you ever code using any programming language? ____
5 Select occupation
a Developer
b Project manager
6 <Question should appear only if answer to 5 is b> years experience in project management ________
Let's say we only have the following constraints:
You want to define each question exactly once
A question can depend on any answer of any previously asked question
Then I propose the following generic solution:
// Each question has an id, a text and a condition depending on previous answers:
var questions = [
{id: "name", text: "What is your name?"},
{id: "code-java", text: "Did you ever code in Java?"},
{id: "code-java-years", text: "How many years?", condition: answers => answers["code-java"] == "yes"},
{id: "code-other", text: "Did you ever code using any programming language?", condition: answers => answers["code-java"] == "no"},
{id: "occupation", text: "Select occupation?"},
{id: "experience-management-years", text: "Years experience in project management?", condition: answers => answers["occupation"] == "Project manager"}
]
// Ask all questions whose conditions evaluate to true and collect the answers:
var answers = {};
questions.forEach(question => {
if (!question.condition || question.condition(answers)) {
answers[question.id] = prompt(question.text);
}
});
console.log(answers);
You probably would want to add more details to each questions such as a validation function, a type (boolean, text, selection, ...) etc.
If you need to store and transfer your questions as plain JSON, you would need to replace your condition functions with a data structure such as conditions: [{id: "code-java", operator: "equals", value: "yes"}] which is evaluated by
operators = {
'equals': (answer, value) => answer == value,
'regex': (answer, value) => new RegExp(value).test(answer),
...
}
conditions.every(condition => operators[condition.operator](answers[condition.id], condition.value))

Is using an Array.map as a foreach good practice? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I'm already using an Array.map, but with the same data, I need to do some other calculations. Should I do those calculations within the map or do it in a for each after the map?
return res.data.map(function (obj) {
if(obj.status.id == 6 || obj.status.id == 5){
dateDifference(obj.created_at,obj.closed_at);
}else{
$scope.open++;
}
return {
"id":obj.id,
"subject": obj.subject,
"requester": obj.requester.name,
"assigned": obj.assigned ? obj.assigned.name : '',
"priority": obj.priority.name,
"status": obj.status.name,
"category": obj.category.name,
"created_at": moment(obj.created_at).utcOffset("06:00").format('lll'),
"updated_at": moment(obj.updated_at).utcOffset("06:00").format('lll')
}
})
I don't see it as a 'good practice', but I don't see it as a bad practice either. Fact is, .map() is designed to both iterate and create a new resulting array.
Perhaps the answer lies in its definition.
From the JS website :
"The map() method creates a new array with the results of calling a
provided function on every element in this array."
From the PHP website (for fun) :
"array_map() returns an array containing all the elements of array1
after applying the callback function to each one."
Nothing keeps you from doing what you want in that callback function.
If you, personnally, are not comfortable doing that, you could achieve the same thing doing a 'for each' while building your own new array. Which is probably what I would do in your specific case. I'd rather do that than have to iterate 2 times over my array.
Though, as Bergi mentionned, it is a better practice to iterate twice over the array if it makes sense sematically.
If performance were to become an issue (iterating twice on a long array). Here is what I would be inclined to do :
for (var i=0; i<myArray.length; i++) {
doStuffA(myArray[i]);
doStuffB(myArray[i]);
}
which is quite clear semantically. Instead of iterating twice.
Of course, some pleople might (will probably) disagree with me.

Categories