Posts by Luiz Felipe • 32,886 points
746 posts
-
6
votes3
answers358
viewsA: How to generate random hexadecimal colors with Javascript?
In a row, you can do it like this: '#' + Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0'); Brief explanation of the above expression: The function Math.floor round the number down…
-
1
votes1
answer227
viewsQ: Error unstructurating value in function: Typeerror: Cannot read Property of Undefined
I would like to understand why this mistake happens: Uncaught TypeError: Cannot read property 'name' of undefined at logName (<anonymous>:1:24) at <anonymous>:5:1 Code: function…
-
1
votes1
answer227
viewsA: Error unstructurating value in function: Typeerror: Cannot read Property of Undefined
It is known that structuring is nothing more than syntactic sugar for common operations involving access to objects (which includes the indexing of arrays). Therefore, the code: function logName({…
-
3
votes2
answers85
viewsA: Formatting to number of decimals dynamically using Python
One option is to create the format string dynamically and then use it in conjunction with the method format. Sort of like this: n = 17 fmt_str = f"{{:.{n + 1}}}" print(fmt_str) # {:.18} Note that I…
-
2
votes2
answers52
viewsA: Calculation of discount in Javascript
To "discount" 10% of a value, you can do something like this: desconto = valor * 0.1; // 10% do valor descontado = valor - desconto; // 90% do valor (10% de desconto) Or simply calculate the…
javascriptanswered Luiz Felipe 32,886 -
6
votes1
answer140
viewsA: How to deal with Undefined (or null) union in Typescript?
This is happening because the kind of find is always the union of type of array elements and undefined. So, for example, if you have an array of the type Array<number> and invoke find, the…
-
0
votes1
answer127
viewsA: Array map and asynchronous functions
Are you using the map as a way to iterate over each element of the array. Let’s see its code: allData.slice(0, 5).map(async function(story) { // ... let itemRes = await axios.get('...') const…
-
3
votes2
answers88
viewsA: How to save the output (stdout) of another program to a file using Python?
According to the documentation of os.system: In Unix, the return value is the output status of the encoded process in the format specified for wait(). Note that POSIX does not specify the meaning of…
-
4
votes1
answer228
viewsA: What is the difference between using classname, classList.toggle() and classList.add()?
The estate className is a string that contains all classes of an element. For example: const el = document.querySelector('div'); console.log(el.className); //=> foo bar baz // Se modificarmos a…
-
2
votes2
answers57
viewsA: Why, in addition to printing the expected result, console.log also prints Undefined?
This happens because the browser Console (or some REPL - like the one in Node.js) displays the evaluation result of the code that will be evaluated in it. We assume you insert the expression 4 + 4…
-
3
votes2
answers52
viewsA: Call and apply methods in functional composition
First, one must understand what the function is compose which is implemented by the code. Note that it expects two arguments (two functions) and will return a new function - a composite function…
-
6
votes2
answers218
viewsQ: Alternative to __filename and __dirname in Node.js with Ecmascript Modules
From more recent versions of Node.js, you can use the Ecmascript Modules standard (instead of the ancient Commonjs) for importing modules via extension .mjs or field type defined as module in the…
-
4
votes2
answers218
viewsA: Alternative to __filename and __dirname in Node.js with Ecmascript Modules
Equivalent to __filename There is a import.meta.url, which returns the URL (do not confuse URL with path, or path in English) of the current file under the protocol file:. An example:…
-
1
votes2
answers64
viewsA: Removing dynamic rowspan lines in table
Once the user clicks on the remove button the selected lines, some steps need to be performed. First, we want to get the element that the user selected. For this, we do something like: const input =…
-
1
votes1
answer266
viewsA: Floating promise check in Typescript Eslint (no floating Promises)
Remember that all asynchronous function in Javascript returns (always) a Promise. Thus, it is ideal that you treat it properly (since it will be solved at another time of execution of the code),…
-
4
votes2
answers108
viewsA: How to get the product to scale two vectors in Javascript?
If you are on Node.js[Commentary], install the library through a package manager. In Node.js, the most common package managers are npm (which is already installed by default with Node.js) and Yarn,…
-
5
votes2
answers149
viewsA: How to swap the last character in a string?
First, if you just want to "swap" the last string value, the for is not even necessary. Following the logic of the question code, could do so: getNum[getNum.length - 1] = " "; However, this doesn’t…
-
3
votes1
answer40
viewsA: How to make a Sort of a converted Nodelist to array?
The estate <elm>.style.order returns a string with the value set in the CSS property order of the element in question. Since it is a string, you should worry about converting it to the…
-
3
votes1
answer264
viewsA: How to increase and decrease the speed of a video?
To control the speed of a video being displayed in the tag <video>, you can use the property playbackRate. The pattern of this property is 1. Thus the value of 1.5 would represent 150% of the…
-
4
votes3
answers169
viewsA: What is the loading="Lazy" attribute for images and iframes?
What is the attribute for loading in the images? To mismatch the standard image loading behavior in an HTML document. The attribute loading is an enumeration that you may have two values: eager,…
-
2
votes0
answers32
viewsQ: What are and what are the main differences between pull Parsing and push Parsing?
I was looking for a parser for Markdown implemented in Rust and I ended up encountering two terms which I do not have the slightest familiarity: pull Parsing push Parsing As far as I know, it’s two…
-
9
votes2
answers144
viewsA: How does changing the prototype of the String.prototype.toString() method affect this code in Javascript?
This happens because, according to the specification, the method String.prototype.split converts the value this to string using the operation ToString. According to step 3 of the algorithm in…
-
4
votes2
answers70
viewsA: Array method not available? "Sort is not a Function" error when applying it to Nodelist
The problem is you’re not working with a Array, but rather with a NodeList. Methods such as the getElementsByClassName or the querySelectorAll do not return an array, but rather a collection of DOM…
javascriptanswered Luiz Felipe 32,886 -
1
votes1
answer51
viewsA: Intellisense in the return of Javascript function in Vscode
You can use a Jsdoc comment for this. See: function tanque(altura) { this.altura = altura; } /** @type {Map<string, tanque>} */ const objMap = new Map(); Basically, according to the definition…
-
1
votes1
answer105
viewsA: What’s the difference between npm i -g create-next-app for npx create-next-app?
There is no "difference". They are different commands, so they have different functions. Therefore it makes no sense to ask which differences and which one is more recommended. Both are equally…
-
4
votes1
answer58
viewsQ: Why does a function accept a reference instead of returning a value?
Consider the code snippet below: int num; printf("Enter a number: "); scanf("%d", &num); I understand that by passing &num to the second argument of scanf(), step the variable reference num,…
-
4
votes1
answer68
viewsA: Loop of promises does not return JSON in Node.js
The problem is here: const loadEvents = arrayOfEventsWithDateIniAndDateEnd.map( async event => await searchEvent(event).then(result => console.log(result)) ); return res.json(loadEvents); Note…
-
7
votes1
answer86
viewsQ: How does async/await work in Rust?
The idea of async/await has become common in several languages (C#, Javascript etc). It seems that Rust recently (in the 2018 edition of Rust) adopted the idea of async/await, together with the…
-
9
votes2
answers334
viewsA: What is a Murmurhash?
Murmurhash (Murmur hash algorithm family) is a non-cryptographic hash with a focus on high performance, optimization and collision resistance. Introducing To understand the motivation behind…
hashanswered Luiz Felipe 32,886 -
5
votes1
answer179
viewsA: What are the main differences between Arrow Function and Closures (anonymous functions) in PHP?
Influence of fashion that Arrow functions in Javascript became, no doubt. In short, the differences are: Syntactic difference (anonymous functions are syntactically different from new functions in…
-
1
votes2
answers97
viewsA: React components that receive ownership of an object as content do not update, how to deal with it?
As stated in documentation of hook useState, React uses the static method Object.is to determine whether two values are equal. The component will only be updated if the unevenness between the values…
-
1
votes2
answers57
viewsA: Regex passes the test site but the code does not work
In accordance with the another answer already scored, you must escape the backslashes in a regular expression built from the constructor since this is a necessity of the strings themselves. And the…
-
6
votes1
answer107
viewsQ: What are the advantages and disadvantages of encapsulated errors types like "Result"?
I’m learning Rust and one of the things that made me curious is the absence of exceptions. Unlike languages such as C#, Java, Javascript, etc., which have exceptions, in Rust this does not exist. If…
-
3
votes1
answer303
viewsA: How to block printscreen on a web page?
There’s no way. The HTML, CSS and Javascript of any website are executed in a type of sandbox which the browser creates for each "tab". If the browser itself, as an application, already prevents…
-
14
votes4
answers486
viewsQ: How would an algorithm work to prevent attempts to trick word blocks (strings)?
Let’s say I develop an application that allows the creation of arbitrary records (no matter the subject). However, for some reason, I have decided to block the use of the word batata in the title of…
-
6
votes1
answer99
viewsQ: What are the differences between String.prototype.match and String.prototype.matchAll methods?
Historically, Javascript relies on the method String.prototype.match to perform, for example, string searches through a pattern via regular expression. However, starting with Ecmascript 2020,…
-
4
votes1
answer61
viewsA: Is there a difference between list and "Symmetric array destructuring"?
PHP has the language building list(), which is used to unstructure values from within an array. That is, with list(), you can unpack values from within an array without using the index or key after…
-
2
votes3
answers105
viewsA: Doubt about Python list
There’s a conceptual error in your algorithm: 1: def verificar_lista(lista): 2: itens = lista 3: for i in range(len(itens)): 4: if itens[i] not in itens: 5: return False 6: else: 7: return True See,…
-
2
votes1
answer85
viewsA: Should I avoid using "optional chaining" within the dependencies of a Hook?
Like the optional chaining is a relatively recent addition to Javascript (standardized with Ecmascript 2020), Typescript (depending on the option target) can issue the code in order to function in…
-
12
votes1
answer528
viewsA: What does "?" interrogation mean in accessing the properties of an object?
It’s called optional chaining (optional chaining). It was introduced in Ecmascript 2020. Is analogous to the operator ., so that allows you to access properties of objects. The difference is that it…
-
6
votes1
answer132
viewsQ: What are algebraic data types (algebraic data types or Adts)?
Eventually I read in some articles related to functional programming the term algebraic data types, but I don’t really know what they are and I end up getting a little lost. What are algebraic data…
-
6
votes2
answers2766
viewsA: What is a string template (literal string declared with "`" grave accent) for in Javascript?
The grave accent delimits a new type of literal string in Javascript, called string template (or literal template). Introduced in Ecmascript 2015 specification (ES6). Among the possibilities of a…
-
6
votes1
answer118
viewsA: How to adapt a function that only accepts callback to the promise interface in Javascript?
You were right: you can use promises to avoid the callback Hell (and avoid callbacks in general). Generally, Promise is the ideal way to deal with asymchronism in modern Javascript, since they allow…
-
11
votes1
answer215
viewsQ: Why use a regular expression "compiled" (re.Compile) in Python?
In a another question of this site, I noticed that although the two responses made use of regular expressions, different paths were taken: One of them used the function re.search to carry out the…
-
4
votes2
answers277
viewsA: How to capture a number in a string using regular expressions (or similar method) in Python?
You can use the following regular expression: r"(\d+,\d+)" See on Regex101. It will select any number contained in the string (being , decimal separator). If numbers can appear in other parts of the…
-
1
votes2
answers49
viewsA: How do you sum all the values of the vector in Python?
Once you have a numerical list, you can use the built-in function sum to add the elements. For example: total = sum([1, 2, 3]) print(total) # 6 However, note that in your code, you are creating a…
pythonanswered Luiz Felipe 32,886 -
1
votes1
answer20
viewsA: Why declare the timeout ID outside the callback of the mocking function?
Notice that you, before creating a new timeout (using the setTimeout), must remove the timeout previous using the function clearTimeout. Let’s take the example of code that nay works:…
-
3
votes2
answers44
viewsA: How to take the value typed in an input and then add it to a Javascript URL?
To capture the value of <input>, you can use the querySelector to, from the field selector, get your Javascript object and then use the property value to get the current value. So: const btn =…
-
2
votes2
answers21
viewsA: Problem using loop addeventlistener
The addEventListener expects to receive a function in your second argument. However, note that you are calling for the function (before passing it to the addEventListener). Behold "Calling…
-
3
votes1
answer119
viewsA: Problem using map with async and await in Javascript
The first thing is not to use map to perform common iterations. The map, as its name says, it is used to map an array in another array. Note that although the map always return a new array, you are…