Prettier space before => in arrow functions - eslint

I am wondering is there a way to config prettier to not inserting white space before arrow symbol in arrow functions. in other words: const f = ()=> {}; would be a valid format for prettier and eslint.

Related

Dynamic call of chalk with typescript

I am using typescript and want to call the chalk method dynamically, see my code :
import chalk from 'chalk';
const color: string = "red";
const message: string = "My Title";
const light: boolean = false;
const colorName = `bg${capitalize(color)}${light ? 'Bright' : ''}`;
console.log(chalk[colorName](message));
So, the color function takes as a value the color of the background of the message. The message is the content and the light is the boolean used to know if the background should have its bright version used.
The problem is that typescript throws this error :
Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'ChalkInstance'.
on the chalk[colorName] part.
I already tried to put (chalk[colorName] as keyof ChalkInstance). And already looked at this post (which is the basically the same problem). Obviously, the solutions answered aren't working with my case.
There are a few things you need to do.
Remove the redundant explicit types from your variables color, message, and light. Doing so is not only unnecessary, it actually interferes with TypeScript properly inferring the literal value of those types. In other words, if you define const color = "red"; TypeScript will know, because it is a const, that it will never change and it can always be treated as the string literal "red" instead of the more generic string. (As a general rule, you should never explicitly define the type of a const variable.)
const color = "red";
const message = "My Title";
const light = false;
Make sure your capitalize() function properly defines its return type. In this case, there is actually an awesome built-in utility type Capitalize<> which you can use here. In combination with a TypeScript generic, you can define the function in such a way that TypeScript knows that e.g. if "red" is what goes in, "Red" is what comes out.
function capitalize<S extends string>(c: S) {
return c.replace(/\b\w/g, firstLetter => firstLetter.toUpperCase()) as Capitalize<S>;
}
Use the as const assertion when you define colorName (and any other similar variables you may need to define). If you don't do this, the type of colorName will be inferred as string, which is no good for indexing chalk. With as const, you are basically telling TypeScript to treat the resulting expression as a literal string value. In this case, the type of colorName becomes "bgRedBright" | "bgRed", both of which are valid indices of chalk.
const colorName = `bg${capitalize(color)}${light ? 'Bright' : ''}` as const;
^^^^^^^^
When you put it all together:
import chalk from 'chalk';
const color = "red";
const message = "My Title";
const light = false;
function capitalize<S extends string>(c: S) {
return c.replace(/\b\w/g, firstLetter => firstLetter.toUpperCase()) as Capitalize<S>;
}
const colorName = `bg${capitalize(color)}${light ? 'Bright' : ''}` as const;
console.log(chalk[colorName](message));
Edit: It's possible in the future that you would need to define your color variable in such a way that it is dynamic and not just a hard coded literal "red" value. In that case you need a way to satisfy TypeScript that color will always be something that is valid given all the other inferences that we just set up.
Here, we actually do want to explicitly define a type for certain variables, particularly let and function arguments. Fortunately, chalk provides a very useful type for this case, ForegroundColor which is essentially all of the valid "base" colors and happen to be compatible with BackgroundColor when put into the form `bg${ForegroundColor`, which is exactly what we need here.
import chalk, { ForegroundColor } from 'chalk';
let color: ForegroundColor = "red";
color = "blue";
We could even improve our capitalize() function by more strictly controlling what the type of the argument can be:
function capitalize<S extends ForegroundColor>(c: S) {
return c.replace(/\b\w/g, firstLetter => firstLetter.toUpperCase()) as Capitalize<S>;
}
Another playground example that puts those further improvements into practice.
I recommend Colors.ts for TypeScript
npm install colorts
import 'colorts/lib/string';
console.log('hello'.green); // outputs green text
console.log('i like cake and pies'.underline.red) // outputs red underlined text
console.log('inverse the color'.inverse); // inverses the color
https://github.com/shaselle/colors.ts
I found the answer to my question myself. The problem was that the colorName variable was of type any and chalk couldn't recognize it as an index of the chalk class. Here the value of the colorName variable could contain all the value of the backgroun colors whether they were bright or not.
I then had two solutions :
Hard code all the values of the colors (which would take a long time)
Find the type representing the colors and explicit set as the type of the colorName variable
My solution is close from the second idea, however, the Chalk library doesn't provide a type for the colors. However, we can import the explicit list of all the BackgroundColors. Then, we only have to asign the type of these keywors as the type of the colorName variable.
import { BackgroundColor } from 'chalk';
import chalk from 'chalk';
const color: string = "red";
const message: string = "My Title";
const light: boolean = false;
const colorName = `bg${capitalize(color)}${light ? 'Bright' : ''}` as typeof BackgroundColor;
console.log(chalk[colorName](message));
PS: Note that the type of the variabkes color, message and light are hard-coded. On the application, these values are dynamic, that's a way to make it more clear.

What are the uses of an underscore in Haxe?

What are the uses of the underscore in Haxe?
I see that I can use it in loops and in array and map comprehensions when I don't care what the counter is, for example:
var a = [for (_ in 0...5) Math.random()]; // 5 random nums
Are there any other places where it's commonly used?
It's generally to denote values that indeed exist, but are not used in the code. Other uses would include:
function arguments that are not used:
button.addListener('click', function (_) trace('clicked!'));
enum constructor arguments that are ignored:
var o = haxe.ds.Option.Some(5);
switch o {
case None: trace('no value');
case Some(_): trace('some value');
}

Why "let" es6 harmony works only with use strict?

This code:
var x = 8,
y = 12;
let ( x = 5, y = 10) {
return x + y;
}
..gives "SyntaxError: Illegal let declaration outside extended mode"
But with "use strict" it works fine.
So it's interesting why 'let' first integrated with "use strict" mode ? (according to http://kangax.github.io/compat-table/es6/#nodeharmony)
let is not a reserved word in ES3-era JavaScript. For instance, you could do this:
var let = 5;
which would declare a variable called let. The ES5 spec was forward looking, and made keywords they expected to use in the future reserved inside strict mode functions. So in the ES6 world, they can parse let as a keyword, but only inside strict containers. Outside strict containers, backwards compatibility demands that let be treated as an identifier, not a keyword.

Resharper settings for method chaining

Is it possible to configure resharper to chop all methods in a method chain
e.g.
var query = list.Where(x => true).Select(x => x);
becomes
var query = list
.Where(x => true)
.Select(x => x);
If not, then is it possible to configure resharper to ignore method chains when formatting? So I can chop the text manually without having to worry about resharper re-formatting it.
Unfortunately, there is no way to align .Where under list.
As for chopping, there is an option in ReSharper | Options -> Code Editing | C# | Formatting Style | Line Breaks and Wrapping -> Line Wrapping called Wrap chained method calls. If you set it to Chop always, it would chop, but it uses a slightly different formatting:
var query = list.Where(x => true)
.Select(x => x);
If you leave it to Chop if long (default value), then it wouldn't re-chop your code unless it would be very long (more than Right margin option, which is in the same option group mentioned above).

coffeescript version of string.format, sprintf() etc. for javascript or node.js

How do I string.format() or sprintf() in coffeescript?
So there's 2 things going on here. First is interpolation, which coffeescript directly supports using double-quoted string literals and ruby style syntax like this:
"The #{speed} #{color} #{animal} jumped over the lazy dog"
That will replace the placeholders with the corresponding variables from the local scope. That's the idiomatic way to handle string interpolation in coffeescript (and ruby).
Second is the formatting, which you should probably handle separately if you want to get numbers with specific decimal places, thousands separate with commas, leading zeros, or that sort of thing. However, CoffeeScript can interpolate the formatting as well, so you could do
"Free shipping on orders over #{currency(freeShipAmount)}"
For other features with C-style formatters, have a look at JavaScript sprintf (which I found on this answer)
This seems to do the trick:
String.prototype.format = ->
args = arguments
return this.replace /{(\d+)}/g, (match, number) ->
return if typeof args[number] isnt 'undefined' then args[number] else match
Translated using some javascript from fearphage
Which can then be used like this:
fmt = "<p>{0} {1} (<a href='mailto:{2}'>{2}</a>)</p>"
mystring = fmt.format "Fred", "Flinstone", "fflinstone#bedrock.gov"
mystring would then be:
<p>Fred Flinstone (<a href='mailto:fflinstone#bedrock.gov'>fflinstone#bedrock.gov</a>)</p>
Using the #{var} approach (while perfect for example given) doesn't work with a string that needs to be recycled several times. In a looping situation for example:
HTML_header = fs.readFileSync('includes/notify/header.html').toString()
HTML_managerOpen = fs.readFileSync('includes/notify/managerOpen.html').toString()
HTML_student = fs.readFileSync('includes/notify/student.html').toString()
HTML_managerClose = fs.readFileSync('includes/notify/managerClose.html').toString()
HTML_footer = fs.readFileSync('includes/notify/footer.html').toString()
HTML_final = HTML_header
getter2 = (r, callback) ->
HTML_final += HTML_managerOpen.format r.EMAIL, r.FNAME, r.LNAME, r.STUDENTS.length, r.PHONE, r.MEMAIL, r.MFNAME, r.MLNAME
async.forEachSeries r.STUDENTS, getter3, (err) ->
HTML_final += HTML_managerClose
callback null
getter3 = (r, callback) ->
HTML_final += HTML_student.format r.EMAIL, r.FNAME, r.LNAME, r.PHONE, r.DESCRIPTION, r.ENROLLED, "", "", "", "", "", "", r.CERTEXAMSCORE, r.COIKEY
callback null
async.forEachSeries results, getter2, (err) ->
cback null, HTML_final + HTML_footer
The idiomatic version of the accepted answer:
String::format = (args...) ->
#replace /{(\d+)}/g, (match, number) ->
if number < args.length then args[number] else match

Resources