What is meaning of the 2 and never param in comma-dangle? - eslint

What is the usage of this ?
"comma-dangle": [ 2, "never" ],
What is 2 and never here?

The first item 2 is a generic setting for any ESLint rule. When configuring rules you can set the severity level of the rule. You can use the numeric value or string value, both mean the same thing:
0 ("off") to turn off the rule, so it does not trigger.
1 ("warning") to produce a warning if the rule is breached.
2 ("error") to produce an error if the rule is breached.
For ESLint itself there is no difference between warnings or errors. In both cases your code does not conform to a rule. However, some tools might differentiate. It is common for build tools to fail the build if errors are encountered but still produce a successful build if there were warnings.
It is usually a good idea to leave relatively minor things as warnings only and serious problems as errors. For example, stylistic rules like spaces around = might just produce a warning, while more serious issues like unreachable code might instead be errors because it is a potential bug.
The "never" is a specific setting for the comma-dangle rule. Some rules are only a toggle on/off (with "on" being warning/error level) while others have extra settings. The comma-dangle rule can be configured for when and where dangling commas are allowed. The value "never" means that they should never appear. From the documentation:
Examples of incorrect code for this rule with the default "never" option:
/*eslint comma-dangle: ["error", "never"]*/
var foo = {
bar: "baz",
qux: "quux",
};
var arr = [1,2,];
foo({
bar: "baz",
qux: "quux",
});
Examples of correct code for this rule with the default "never" option:
/*eslint comma-dangle: ["error", "never"]*/
var foo = {
bar: "baz",
qux: "quux"
};
var arr = [1,2];
foo({
bar: "baz",
qux: "quux"
});

Related

How can I get the multiple subchild objects from json using nodejs?

I am trying to fetch the specifice object from my json files. For now I can fetch any tag instead of the "p" tag from it. you can please have look at the screenshot I have attached.
Click to open the json file
this is how I'm trying to fetch p tag:
'use strict';
const fs = require('fs');
var data = JSON.parse(fs.readFileSync('./me.json'));
data.Document.Decision.forEach(x => {
console.log(x.Texte_Integral.p);
});
This is a weird way of organizing your block, I recommend rewriting/reorganizing the JSON so it is more easily accessible.
There are a few things you have to know before this answer makes sense:
Array indexes
[] resembles an array, you can access each index by doing array[index], for example:
let arr = ['zero', 'one', 'two'];
console.log(arr[0]); //expected output: 'zero'
Bracket Notation
In JavaScript, there are two ways to access a variable's value, either by dot notation or bracket notation. As far as I know, the only differences these have are just the ability to use dynamic input and characters you can't usually use inside a variable's name, for example:
let obj = {
var1: "this is variable1",
var2: {
var3: "this is variable3 inside variable2"
}
}
console.log(obj.var1) //expected output: "this is variable1"
console.log(obj[`var1`]) // expected output: "this is variable1"
console.log(obj.var2.var3) //expected output: "this is variable3 inside variable2"
console.log(obj[`var2`].var3) // expected output: "this is variable3 inside variable2"
console.log(obj[`var2`]["var3"]) // expected output: "this is variable3 inside variable2"
Bracket notation also works inside objects, thus why the variable names inside as a string, like "Document", works.
let obj2 = {
"var1": 1,
["var2"]: 2,
var3: 3
};
console.log(obj2["var1"]) // expected output: 1
// console.log(obj2"var1") is INVALID and does not work
console.log(obj2["var2"]) // expected output: 2
console.log(obj2.var3) // expected output: 3
Coming to the solution
data.Document.Decision.forEach(x => {
console.log(x.Texte_Integral[0].p)
});
This returns ["ASDFDSFDSFSD"], if we wanted to use it as a string and not an array (remember the brackets) then we would access the first index of the array. This would be done by adding [0] at the end.
❕ Solution
data.Document.Decision.forEach(x => {
console.log(x.Texte_Integral[0].p[0])
});
Future Information
About stackoverflow, next time, please share code via code blocks and not screenshots. Thank you for coming to ask your question, we just want it to be easier for us to both understand and access the code! I had to type the whole thing out myself, which could've been easily avoided by just copy/paste-ing the code. If you don't know how to do certain things in the textbox, see the formatting help page.

Is there extension or function to know bracket declaration when focued close bracket

I want to know declaration of open bracket when focused close bracket.(ex. if (...) ).
I know emacs, vscode, vim are has goto declaration function. But, they needs 1 action(type M-.(emacs),F12(vscode),%(vim)). I don't want to type some key each time. So, I want to know declaration of bracket with 0-action.
I don't care how displays in declaration(pop-up, mini buffer, status bar)
Background:
I'm in fixing legacy code. The code is too much nested with ifs and fors and whiles.
By much nested, end of code are many continus close bracket(}) like below.
for (var item in list){
if (cond1) {
...
while( cond2 ) {
...
if (cond3) {
...
} else {
...
}
}
}
list.append(item)
}
}
I usually mistake cond2 and cond3, created bugs, don't show log messages, and spent much time.
This question was translated by google translator. so, if you couldn't recognise this, please comment.
When your cursor is on a bracket, the other one is highlighted automatically if you have :help matchparen enabled.
When your cursor is on a bracket, you can jump to the opening one with :help %.
To quote Mass:
Yes- the plugin match-up has this feature:
https://github.com/andymass/vim-matchup
Using the option
let g:matchup_matchparen_offscreen = { 'method': 'popup' }
There is also the ability to show the match in the statusline (the
default):
let g:matchup_matchparen_offscreen = { 'method': 'status' }`

Updating ArangoDB sub document

I am currently evaluating whether ArangoDB can be a future alternative for us. As a part of this evaluation I am porting code that talks to our current NoSQL db into code that speaks ArangoDB. While it has been a fairly smooth ride so far, I am having surprisingly difficult to wrap my head around on how to update sub documents. Assuming we have something like this:
{
"_key": "12345",
"subdoc": {
"0": {
"num_sold": 6,
"other_attribute": "important"
},
"1": {
"num_sold": 4,
"other_attribute": "important"
}
}
}
What I would like to accomplish now it to atomically increase num_sold.
A very first naive approach was of course to try something similar to:
FOR d in ##collection
FILTER d._key == "12345"
UPDATE d WITH { subdoc.0.num_sold : subdoc.0.num_sold + 1 } IN ##collection
RETURN d
(Spoiler alert for the copy-pasters out there: move on. This snippet will just make your life miserable.)
This obviously didn't work and most likely for more than one reason. Arango does not seem to like me referencing the attribute using dot notation, the attribute starting with a number ("0") might also be an issue etc. While having found an example here it seemed both a bit complicated and convoluted for what I am trying to do. There is also another discussion here that is close to what I would like to do. However, the proposed solution in that discussion uses the keyword OLD that creates an error in my case as well as the code replacing all keys in "0".
1) What is the best way to atomically increase num_sold?
2) When is an operation atomic? (Trying to stay away from transactions as long as possible)
3) When can the dot notation be used and when can it not be used?
4) Can I bind parameters to an attribute? For instance letting some #attribute be subdoc.0.num_sold?
Thanks!
ArangoDB can't parse the query if you use numbers in the dot notation.
However there is an easy way - simply use brackets instead of the dot notation as you did.
Example - not working:
db._query(`
LET testdoc = {subdoc: {"0": "abc"}}
RETURN testdoc.subdoc.0`)
ArangoError 1501: syntax error, unexpected integer number,
expecting identifier or bind parameter near '0' at
position 1:60 (while parsing)
Example - fixed:
db._query(`
LET testdoc = {subdoc: {"0": "abc"}}
RETURN testdoc.subdoc.[0]`)
[
"abc"
]
Using bind variables - not working:
db._query(`
LET testdoc = {subdoc: {"0": "abc"}}
RETURN testdoc.subdoc.#bv`, {bv: 0})
ArangoError 1501: syntax error, unexpected integer number,
expecting identifier or bind parameter near '0' at
position 1:60 (while parsing)
Using bind variables - fixed:
db._query(`
LET testdoc = {subdoc: {"0": "abc"}}
RETURN testdoc.subdoc.[#bv]`, {bv:0})
[
"abc"
]

Does assert.equal offer any advantages over assert (assert.ok)?

In this question I refer to the assert module that is included within the node.js core.
As far as I can tell the following two assertions are pretty much identical:
assert.equal(typeof path, "string", "argument 'path' must be a string");
assert(typeof path === "string", "argument 'path' must be a string");
Upon failure both variations report the same message:
AssertionError: argument 'path' must be a string
Are there any notable advantages of the former over the latter in this situation?
Well, depending on the test runner framework, assert.equal will probably give you a more descriptive error message. For instance, in this case:
assert.equal(typeof path, "string");
assert(typeof path === "string");
the first statement would give you a message along the lines of:
actual: number
expected: string
which already tells you that the test case fails because typeof path is a number.
The latter will only print something like this:
AssertionError: false == true
Also, note that if you want to check for strict equality (===), you should use assert.strictEqual instead of assert.equal.
assert.equal doesn't check for identity, only equality. It's equivalent to:
assert(typeof path == 'string', "argument 'path' must be a string");
The real equivalent would be assert.strictEqual, which uses the identity operator ===:
assert.strictEqual(typeof path, "string", "argument 'path' must be a string");
For typeof, no, there's no difference. You'll run into problems with other data types though:
> assert.equal('test', ['test']);
undefined
> 'test' == ['test']
true
> 'test' === ['test']
false
Both will work.
First, assert uses the coercive == operator, not strict ===
Also, when you read a lot of your unit tests or other people's unit tests, you'll strain your eyes on repetitive syntax. You'll love it when people will write this
assert.equal(aValue, anotherValue) // sexy
/** But you will hate people writing this. **/
assert.ok(aValue == anotherValue) // ugly
In the first case, you can see the condition being checked within the first 9 letters. You don't even need to look further. In the other case, you have to read 20 letters to know what the test is checking. It's more cryptic.
Also, assert.equal is more declarative of your intention than assert.ok.
Imagine you are writing a test for testing a set intersection. You would read better
assert.setIntersect(set1, set2) // wow
assert.ok(setIntersect(set1, set2)); // hm.
To sum it up, the advantage is in readability (thus maintainability) of you unit tests. It's not much, but it helps writing better understandable code.
As alexander said, too, you will have more precise error messages when test fail if you don't specify a message.

Spock label combinations

There | are | so many | Spock | spec examples of how to use its labels, such as:
// when -> then label combo
def "test something"() {
when:
// blah
then:
// blah blah
}
Such label combinations as:
when -> then
given -> when -> then
expect
given -> expect
But nowhere can I find documentation on what the legal/meaningful combinations of these labels are. For instance, could I have:
def "do something"() {
when:
// blah
expect:
// blah
}
Could I? I do not know. What about:
def "do something else"() {
when:
// blah
then:
// blah
expect:
// blah
where:
// blah
}
Could I? Again, I do not know. But I wonder.
I am actually an author of one of the tutorials you have mentioned. I think the best to answer your question would be to really understand what particular labels are for. Maybe then it would be more obvious why certain combinations make sense and other do not. Please refer to original documentation http://spockframework.github.io/spock/docs/1.0/spock_primer.html. It explains really well all labels and their purpose. Also it comes with this diagram:
Which I hope should already tell you a lot. So for instance having both when and expect labels makes not much sense. The expect label was designed to substitute both when and then. The reasoning behind it is well explained in the documentation:
An expect block [...] is useful in situations where it is more natural to describe stimulus and expected response in a single expression.
Spock itself will not allow you to use this combination. If you try to execute following code.
def "test"() {
when:
println("test")
expect:
1==1
}
You will receive an error message like this.
startup failed:
/Users/wooki/IdeaProjects/mylibrary/src/test/groovy/ExampleTest.groovy:
13: 'expect' is not allowed here; instead, use one of: [and, then] #
line 13, column 9.
To my surprise the second of your examples works. However I believe there is really not much gain of using expect here instead of and as I would normally do.
def "do something else"() {
when:
// stimulus
then:
// 1st verification
and:
// 2nd verification
where:
// parametrization
}
The only reason to have expect or and after then is to separate code responsible for verifying the result of executing the code inside when label. For instance to group verifications that are somehow related to each other, or even to separate single verifications but to have a possibility of giving them a description using strings that can be attached to labels in Spock.
def "do something else"() {
when:
// stimulus
then: "1 is always 1"
1 == 1
and: "2 is always 2"
2 == 2
}
Hence, since you are already stating that verification part of the test began (using then block) I would stick to and label for separating further code.
Regarding where label. It works sort of as a loop indicator. So whatever combinations of labels you use before you could always put at the end the where label. This one is not really a part of a single test run, it just enforces the test to be run a number of times.
As well it is possible to have something like this:
def "test"() {
given:
def value
when:
value = 1
then:
value == 1
when:
value = 2
then:
value == 2
}
Using the above, just make sure that your test is not "testing too much". Meaning that maybe a reason why you use two groups of when-then makes a perfect excuse for this test to be actually split into two separate tests.
I hope this answered at least some of your questions.

Resources