How to make javascript function can use after dot - javascript

I'm doing firebase project these days, and i got a question about something.
var citiesRef = db.collection("cities");
citiesRef.where("state", ">=", "CA").where("population", ">", 100000)
Those where() are stick together after dot and i have no idea.
How can i make function or class like that? I don't even know how to search !
I tried to make classes and unnamed functions but it doesn't work.
If i get to know about it, it'll be very useful for me. I really want to know.
Please help please

This is something akin to the Builder Pattern. The idea is to return the object after appending a condition.
Example code (language agnostic):
def where(condition){
self.appendCondition(condition)
return self // Important part
}
The return self enables to chain methods on the same object. Each one returns itself with the new condition appended.

Related

Vanilla JS - hoisting a querySelected variable to Window

I've been researching and trying different solutions to this literally all day.
** EDIT: regarding duplicate post: As I wrote below, a set timeout function has been attempted and successful around the function call. Please, before you close my question, atleast ask that what you’re describing as a duplicate hasn’t already been attempted… or in this case. INCLUDED in my original post. I’m not looking for cred, I’m looking for help. **
I have a reusable function takes in 3 params:
What to wrap,
wrap in what type of element
and the id of the new wrapping element (so I can control access it later.)
Here's a codeSandbox version to help you help me! https://codesandbox.io/s/queryselector-to-globe-jbffk0?file=/index.html
Goal: I'd like to include a querySelector within the function that takes in the id to eliminate the extra step, to ensure the selector is defined after the item is created, and to keep a cleaner code-base. The problem is I keep fighting between a function that's surrounded by parens...
Var wrap = (function(params){...})(window); to potentially give global scope to the queryselector(object ref) I'm trying to create, and a standard es6 function I'm more familiar with... Var wrap = (params) => {...};
import "./styles.css";
const item = document.querySelector(".item");
var wrap = (function (toWrap, wrapper, id) {
wrapper = wrapper || document.createElement("div");
wrapper.setAttribute("id", `${id}`);
toWrap.parentNode.appendChild(wrapper);
// Non-working auto id something to
// window.id = document.querySelector(`${id}`);
return wrapper.appendChild(toWrap);
})(window);
// How can I "store the window.id" just as if it were manually written right here in global scope?
wrap(item, "div", "itemadded");
Note: the window thing I read at: http://markdalgleish.com/2011/03/self-executing-anonymous-functions/
Like I said, I can provide more working code/attempts to show I've made a ton of effort if anyone is wondering.
PS, I'll definitely mark the answer and give upvotes for help.
Thanks in advance!
If your still reading, I've tried simplifying even further, adding a timeout function to ensure that the function takes in toWrap correctly... idk what else to try... :(

Pass Component Name as Argument and then attach method (not working?)

Maybe I'm not using the right terms/names for my searches but I have not been able to find anything on this topic. I would have thought this would be an easy thing to find. What I'm doing is passing a component name to a function and then trying to use the component's name by attaching a method to it. I have confirmed (via Dev Tools) that the name is correctly being passed but when I use the variable and attach the method the specific request does not work. If I 'hard-code' the exact component name to the method it works perfectly. This makes me think the (various) ways I've been trying to attach the method to the variable name is incorrect (see various attempts below). Can you offer some direction here? Thank you.
Passing to Function ...
const grid_name = "grid_GroupA";
console.log(grid_name); // Shows grid_GroupA
msg_max(newItem, grid_name);
Function (only listing relevant parts)
function msg_max(newItem, grid_target) {
console.log(grid_target); // Shows grid_GroupA
// grid_GroupA.data.add(newItem); // This works ...
// grid_target.data.add(newItem); // This does not work
// (grid_target).data.add(newItem); // This does not work
// [grid_target].data.add(newItem); // This does not work
// grid_target + '.data.add(newItem)'; // This does not work
Thank you ...
Edit ...
In my attempt to provide detail I hope I haven't confused the issue.
In essence, my question is if I can type this exact string
grid_GroupA.data.add(newItem);
and it works for my function, how can I place a variable with the exact string "grid_GroupA" in front of ".data.add(newItem);" and have it seen the same as the line of code that works? Maybe my lack of knowledge here is getting in the way but isn't the line of code that works just a string that is then used to 'find' the object? So, if that assumption is correct, how do I create that same string with the variable? If my assumption is wrong I am a willing learner so I will be all ears. Thank you.
I do not see how grid_target is an object. You are passing grid_name(which is a string) to the function, so grid_target will have no data property, because string doesn't have such a member.
P.S. snake_case is bad option for JavaScript, consider using cameCase instead

Document variable in python

If in the middle of my software, i have this variable that i need explain what it is and what is used for, i need document the variable.
I have a background in JS, so that's how i do:
/**
* Explain what the variable is, and what is for.
* #variable {Object} nameOfVariable
*/
var nameOfVariable = []
In the case of python:
# ??
name_of_variable = []
Is there conventions for this type of thing?
Thanks a lot.
Yes there is - this is what I can find
https://www.python.org/dev/peps/pep-0257/
For functions you can add a docstring e.g.
def some_function():
""" Write here a one line summary.
If wanted, then leave a line and write a more detailed one"""
The """ need to be indented correctly to work
However, for hashes #, which is more common after single variables, they don't need to be indented correctly. E.g.
some_variable = Something # This variable is doing this...
Hope that is somewhat helpful.
PEP257 documents so called docstrings which is a string literal which appears as first statement in the definition of a module, class, function or a method. As far as I know if you want to leave some information about a variable you leave regular comments near it. For example:
# This is some variable ...
some_variable = ...
You might find that people document parameters, what a function returns, and so on, but usually variables are not documented in python libraries.
The names should generally be self-explanatory.

nodeJS, MySQL and UTF8

I am trying to write a custom String.Prototype function:
String.prototype.Apos = function () {
var string = this.innerHTML.toString();
return string.replace(/’/g,"'").replace(/“|â€/g,'"');
};
I really just want to write a utf8 string to the browser using javascript, however using decodeURIComponent wont work and so I have just resorted to replacing the apostrophes myself.
So from the examples I've seen I wrote the above function, however it doesnt seem to return anything. When I run the following:
$("span").html(string.Apos);
I don't get a response. I've never written a custom prototype function before so could someone help me out and tell me where Im going wrong?
Do you really need to mess with string.prototype?
You can write a function to do the specific job you want to perform, i.e., replace text.
function replaceQuotes(i, oldHtml) {
return oldHtml.toString().replace(/’/g,"'").replace(/“|â€/g,'"');
}
And then:
$("span").html(replaceQuotes);

Functional JS w/Recursive Functions

Alright, I realize this is probably very beginner-ish for many of you on here, but I'm hoping someone can explain this in a way I can wrap my head around. My question centers around what I've heard is the basis for functional JavaScript - recursion. I was working on a personal project, and found a great use case for one, but I still don't quite get what's going on - need a visual way of thinking through it.
So, here's an example. The problem that's being solved is a simple helper function to find the next sibling in the DOM matching a specific tagname (assume the current element and tagname are passed in when calling the function, i.e. findSibling(this, 'DIV')).
var findSibling = function(el, tagName) {
if (el.nextSibling.tagName === tagName.toUpperCase())
return el.nextSibling;
else
return findSibling(el.nextSibling, tagName);
}
Ok, so this works! Great! But, it took me forever to land here, and it really shouldn't have. I tried whiteboarding it out, the best I can understand is that something like this is happening:
findSibling(<span>, div) ▸ findSibling(<span>, div) ▸ findSibling(<span>, div) ▸ <div>
Assuming we have HTML something like this:
<div></div>
<span></span>
<span></span>
<span></span>
<div></div>
Can anyone help me visualize this a bit more? Any tips/tricks that you may have used when first learning this concept? I'm just looking for that lightbulb...
Also, the one thing I was stuck on for awhile was the second return statement. Why can't I just call the function in the else? Why do I need the return? Seems like it would just call the function with the sibling element.
Thank you!
To explain your second question first, let's rewrite your function a little:
var findSibling = function(el, tagName) {
var match;
if (el.nextSibling.tagName === tagName.toUpperCase()) {
match = el.nextSibling;
} else {
match = findSibling(el.nextSibling, tagName);
}
return match;
}
Both returns in your original code are doing the same thing, returning the tag you're searching for. What's different in each case is how that match is calculated.
To answer your first question, let's look at your code in a different way. Anytime you have a function, you can always replace the function call with the code of the function, with parameters properly replaced. For example:
function hello(text) {
alert('Hello ' + text);
}
hello('to you.');
is the equivalent to
alert('Hello to you.');
So let's do this with your recursive function:
if (el.nextSibling.tagName === tagName.toUpperCase())
return el.nextSibling;
else
if (el.nextSibling.nextSibling.tagName === tagName.toUpperCase())
return el.nextSibling.nextSibling;
else
if (el.nextSibling.nextSibling.nextSibling.tagName === tagName.toUpperCase())
return el.nextSibling.nextSibling.nextSibling;
else
etcetera...
From this you should be able to see how a recursive function hides a loop in itself. This also shows the danger of recursive functions - that they can keep calling themselves without end. Which leads me to wonder - what will happen to your function if el doesn't have a nextSibling?
I like to think as recursion as the mirror effect or the Droste effect, based on the following picture:
Where each level digs deeper into the next one until it reaches a limit. In your case, find the sibling with the desired tag name.
So essentially your base code is the first picture, and the first recursion is the first level. It will go a level deeper until it reaches its goal.
Can anyone help me visualize this a bit more? Any tips/tricks that you
may have used when first learning this concept?
Maybe thinking of an iterative version would help understand:
function findSibling(el, tagName) {
while (el = el.nextSibling) {
if (el.tagName == tagName.toUpperCase()) {
return el;
}
}
}
Also, the one thing I was stuck on for awhile was the second return
statement. Why can't I just call the function in the else? Why do I
need the return?
A recursive function as general rule will have a recursive call and an exit condition. The definition itself is recursive. In your code the exit condition is finding the tagName.
Explaining recursion is hard if you don't understand recursion. The Wikipedia has a good explanation with visualization. http://en.wikipedia.org/wiki/Recursion
Edit: See this question too https://softwareengineering.stackexchange.com/questions/25052/in-plain-english-what-is-recursion
You call a function findSibling to find 'tag'
But it doesnt find tag so it calls function findSibling to find 'tag'
But it doesnt find tag so it calls function findSibling to find 'tag'
But it doesnt find tag so it calls function findSibling to find 'tag'
It retrns tag to its caller
It returns tag to its caller
It returns tag to its caller
It returns tag to its you.
You have tag.
I think the best you can understand is the correct answer to this particular problem. To find something in a nested DOM is only slightly more complex to think about but its the same concept... and almost the same code.

Categories

Resources