ESLINT: params.majorVersion = m[1]; => Use array destructuring.(prefer-destructuring) - ecmascript-6

I'm struggling with an Eslint error about this code :
const m = version.match(/^(\d+)\.\d+\.\d+/);
...
params.majorVersion = m[1];
I have an ESLint error : Use array destructuring.(prefer-destructuring)
I tried different things like
const [,majorVersion] = m;
params.majorVersion = majorVersion
or
const [, majorVersion] = version.match(/^(\d+)\.\d+\.\d+/);
...
params.majorVersion = majorVersion
But solution 1 is more verbose, I can't see how destructuring improves anything here. And the 2nd solution doesn't work when there's no match. I'm starting to think there's a problem with this Eslint rule for this code
Am I missing something ?

Related

how do I change ${....} to black instead of red when I use it within '<div> .......... </div>' in google app script [duplicate]

I know in PHP we can do something like this:
$hello = "foo";
$my_string = "I pity the $hello";
Output: "I pity the foo"
I was wondering if this same thing is possible in JavaScript as well. Using variables inside strings without using concatenation — it looks more concise and elegant to write.
You can take advantage of Template Literals and use this syntax:
`String text ${expression}`
Template literals are enclosed by the back-tick (` `) (grave accent) instead of double or single quotes.
This feature has been introduced in ES2015 (ES6).
Example
var a = 5;
var b = 10;
console.log(`Fifteen is ${a + b}.`);
// "Fifteen is 15.
How neat is that?
Bonus:
It also allows for multi-line strings in javascript without escaping, which is great for templates:
return `
<div class="${foo}">
...
</div>
`;
Browser support:
As this syntax is not supported by older browsers (mostly Internet Explorer), you may want to use Babel/Webpack to transpile your code into ES5 to ensure it will run everywhere.
Side note:
Starting from IE8+ you can use basic string formatting inside console.log:
console.log('%s is %d.', 'Fifteen', 15);
// Fifteen is 15.
Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, nope, that was not possible in javascript. You would have to resort to:
var hello = "foo";
var my_string = "I pity the " + hello;
Prior to Firefox 34 / Chrome 41 / Safari 9 / Microsoft Edge, no. Although you could try sprintf for JavaScript to get halfway there:
var hello = "foo";
var my_string = sprintf("I pity the %s", hello);
well you could do this, but it's not esp general
'I pity the $fool'.replace('$fool', 'fool')
You could easily write a function that does this intelligently if you really needed to
Complete and ready to be used answer for <ES6:
var Strings = {
create : (function() {
var regexp = /{([^{]+)}/g;
return function(str, o) {
return str.replace(regexp, function(ignore, key){
return (key = o[key]) == null ? '' : key;
});
}
})()
};
Call as
Strings.create("My firstname is {first}, my last name is {last}", {first:'Neo', last:'Andersson'});
To attach it to String.prototype:
String.prototype.create = function(o) {
return Strings.create(this, o);
}
Then use as :
"My firstname is ${first}".create({first:'Neo'});
If you are on >ES6 then you can also do:
let first = 'Neo';
`My firstname is ${first}`;
2022 update: Just use the ES6 Template Literals feature. It's fully supported in practically every browser you'll encounter these days. If you are still targeting browsers like IE11 and lower .. well, my heart goes out to you. The below solution I came up with 5 years ago will still work for you. Also, email me if you want a job that doesn't involve catering to old browsers 👍.
You can use this javascript function to do this sort of templating. No need to include an entire library.
function createStringFromTemplate(template, variables) {
return template.replace(new RegExp("\{([^\{]+)\}", "g"), function(_unused, varName){
return variables[varName];
});
}
createStringFromTemplate(
"I would like to receive email updates from {list_name} {var1} {var2} {var3}.",
{
list_name : "this store",
var1 : "FOO",
var2 : "BAR",
var3 : "BAZ"
}
);
Output: "I would like to receive email updates from this store FOO BAR BAZ."
Using a function as an argument to the String.replace() function was part of the ECMAScript v3 spec. See this SO answer for more details.
If you like to write CoffeeScript you could do:
hello = "foo"
my_string = "I pity the #{hello}"
CoffeeScript actually IS javascript, but with a much better syntax.
For an overview of CoffeeScript check this beginner's guide.
I would use the back-tick ``.
let name1 = 'Geoffrey';
let msg1 = `Hello ${name1}`;
console.log(msg1); // 'Hello Geoffrey'
But if you don't know name1 when you create msg1.
For exemple if msg1 came from an API.
You can use :
let name2 = 'Geoffrey';
let msg2 = 'Hello ${name2}';
console.log(msg2); // 'Hello ${name2}'
const regexp = /\${([^{]+)}/g;
let result = msg2.replace(regexp, function(ignore, key){
return eval(key);
});
console.log(result); // 'Hello Geoffrey'
It will replace ${name2} with his value.
I wrote this npm package stringinject https://www.npmjs.com/package/stringinject which allows you to do the following
var string = stringInject("this is a {0} string for {1}", ["test", "stringInject"]);
which will replace the {0} and {1} with the array items and return the following string
"this is a test string for stringInject"
or you could replace placeholders with object keys and values like so:
var str = stringInject("My username is {username} on {platform}", { username: "tjcafferkey", platform: "GitHub" });
"My username is tjcafferkey on Github"
If you're trying to do interpolation for microtemplating, I like Mustache.js for that purpose.
Don't see any external libraries mentioned here, but Lodash has _.template(),
https://lodash.com/docs/4.17.10#template
If you're already making use of the library it's worth checking out, and if you're not making use of Lodash you can always cherry pick methods from npm npm install lodash.template so you can cut down overhead.
Simplest form -
var compiled = _.template('hello <%= user %>!');
compiled({ 'user': 'fred' });
// => 'hello fred!'
There are a bunch of configuration options also -
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
var compiled = _.template('hello {{ user }}!');
compiled({ 'user': 'mustache' });
// => 'hello mustache!'
I found custom delimiters most interesting.
Simply use:
var util = require('util');
var value = 15;
var s = util.format("The variable value is: %s", value)
Create a method similar to String.format() of Java
StringJoin=(s, r=[])=>{
r.map((v,i)=>{
s = s.replace('%'+(i+1),v)
})
return s
}
use
console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'
Peace quote of 2020:
Console.WriteLine("I {0} JavaScript!", ">:D<");
console.log(`I ${'>:D<'} C#`)
Maybe
wrt=(s, arr=[])=>{
arr.map((v,i)=>{s = s.replace(/\?/,v);});
return s;
};
a='first var';
b='secondvar';
tr=wrt('<tr><td>?<td></td>?</td><tr>',[a,b]);
console.log(tr);
//or use tr in html(tr), append(tr) so on and so forth
// Use ? with care in s
String.prototype.interpole = function () {
var c=0, txt=this;
while (txt.search(/{var}/g) > 0){
txt = txt.replace(/{var}/, arguments[c]);
c++;
}
return txt;
}
Uso:
var hello = "foo";
var my_string = "I pity the {var}".interpole(hello);
//resultado "I pity the foo"
var hello = "foo";
var my_string ="I pity the";
console.log(my_string, hello)

Multiple Variable Assignment in Javascript/GAS - Is this the most compact way to do it?

Ok so I have a spreadsheet which we extract a 2d array of values from.
But really I want one variable per line of this 2d array.
The following code does work... but is this the best way to do it?
function testAssignments(){
config = ss.getRange("C2:C6").getValues();//2D Array
result = []
config.forEach(x => result.push(x[0]))
var [a,b,c,d,e] = result;
console.log(a,b,c,d,e);
}
I also tried the line config.forEach(x=> x=x[0]) but that didn't work for some reason.
Use .flat instead of .forEach and .push. If you want a different variable name for each element, there isn't a better way.
const [a,b,c,d,e] = ss.getRange("C2:C6").getValues().flat();//1D Array
//or
const [[a],[b],[c],[d],[e]] = ss.getRange("C2:C6").getValues();

How can I use multi-line matching in a bump2version config file?

I want to use bump2version for a file that looks like this (it's a rust Cargo.toml):
[package]
name = "my_super_package"
version = "0.1.34"
...
[dependencies]
my_other_super_package = { path = "../yadayadayada", version = "0.1.34", registry = "crates-haha" }
...
In the .bumpversion.cfg file, I cannot just use
[bumpversion:file:Cargo.toml]
parse = qv\((?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)
because that would accidentally also change the unrelated version of my_other_super_package that coincidentally has the same version number.
The bump2version docs say that search and replace can handle multi-line specs, so I tried
[bumpversion:file:Cargo.toml]
search = name = "my_super_package"\nversion = "{current_version}"
replace = name = "my_super_package"\nversion = "{new_version}"
but the newlines didn't seem to be matched. I also tried
[bumpversion:file:Cargo.toml]
parse = qv(^version = \((?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+))
but the "^version = " part seems to be ignored.
Help?
wandered same question, and found the answer.
File for bumping Cargo.lock and Cargo.toml (so git tree would be clean after VScode autobumping Cargo.lock file), the trick is to use tab symbols (maybe spaces will work as well, didn't test):
[bumpversion:file:Cargo.lock]
search = name = "my-project"
version = "{current_version}"
replace = name = "my-project"
version = "{new_version}"
so after bumping you get in Cargo.toml:
[package]
name = "my-project"
version = "1.2.2"

Is there an alternative way to filter xml elements without the E4X syntax?

I am trying to compile some old actionscript code (part of flash app) to JS using Jangaroo. Jangaroo does not support the E4X syntax and it fails at things like the double-dot operator .. or the brackets filters a.(CONDITION). So I need to rewrite those portions of code using plain ActionScript.
For the double-dot operator, I used the instead the method descendants() but I could not find alternative way to write the brackets filter.
Here is the original code I had:
B = xml..destination.(#id == someId)
I wrote it now:
B = xml.descendants("destination").(#id == someId)
But I still want to remove .(#id == someId).
I am thinking of something like:
if (xml.descendants("destination").attribute("id") == someId)
{
B = xml.descendants("destination")
}
Is this possible?
So here is how I proceeded. I have not tested its functionality, but the compiler passed it.
var destinations:XMLList = null;
for each (var elm in xml.descendants("destination") )
{
if ( elm.attribute("id") == someId )
{
destinations += elm;
}
}

Syntax error: expecting semicolon before leftbracket

I have the following code at frame one of the top layer:
var level:Array = new Array();
var level[0] = new Object();
I am getting the following error:
Scene 1, Layer 'levels', Frame 1, Line 2
1086: Syntax error: expecting semicolon before leftbracket.
I've looked at many examples which seem to be doing the same thing I'm doing, and I've also tried defining the object separately and then adding it to the array, with the same error. I've also searched for the answer, but all the questions I've found are a little different than this situation.
The syntax/grammar production
var level[0] = new Object();
is invalid.
The var production expects a simple Identifier, not an expression1. The parser was roughly trying to treat the production as var level;[0] = ..; (but failed due to the missing semicolon, and would have failed anyway because [0] = ..; is an invalid production as well).
Try:
var level:Array = new Array();
level[0] = new Object(); // no "var" here so it is a valid grammar production
or, more concisely:
var level:Array = [{}]; // using Array and Object literal notations
1 See AS3.g for that ANTLR production rules. Alternatively, for ECMAScript (from which AS derives), see 12.2 Variable Statement from ES5-Annotated and note that it requires an "Identifier" followed by an optional initializer (=) or another declaration (,) or end of statement (;).
Only is
level[0] = {};
or
level.push({});