ESLint rule to align chained implicit return in arrow function declarations - eslint

ESLint is currently giving me:
const doThings = (id) => doSomething(
`id:${id}`,
"foobar",
)
.then(doOtherThing)
I want to continue to allow implicit returns, with implicit-arrow-linebreak set to "beside" as above, but I don't like the mismatch in indentation between the closing paren and the next chained call.
Is there a rule or combination of rules (whether built in or via a plugin) that can achieve this?
I don't mind whether it's purely indentation:
const doThings = (id) => doSomething(
`id:${id}`,
"foobar",
)
.then(doOtherThing)
or forcing it via parens:
const doThings = (id) => (
doSomething(
`id:${id}`,
"foobar",
)
.then(doOtherThing)
)
or disallowing implicit returns when they span multiple lines:
const doThings = (id) => {
return doSomething(
`id:${id}`,
"foobar",
)
.then(doOtherThing)
}

Related

Tiptap how to create a paragraph (p) on Shift-Enter, instead of a br?

Using TipTap, I'm trying to avoid adding a <br />, but create a <p></p> instead, with the focus inside that <p>|</p> when the user hit shift-Enter but I can't make it work.
Here's what I did so far:
new (class extends Extension {
keys () {
return {
'Shift-Enter' (state, dispatch, view) {
const { schema, tr } = view.state
const paragraph = schema.nodes.paragraph
console.log(tr.storedMarks)
const transaction = tr.deleteSelection().replaceSelectionWith(paragraph.create(), true).scrollIntoView()
view.dispatch(transaction)
return true
}
}
}
})()
How can I do this?
I don't know if this is still relevant but as I was looking for the same thing, I found two ways to make this work.
NOTE:
I'm using tiptap v2, if that's not a problem, then:
I overrode the HardBreak extension, since it's the one that use the Shift-Enter keybinding. It looks something like;
const CustomHardBreak = HardBreak.extend({
addKeyboardShortcuts() {
return {
"Mod-Enter": () => this.editor.commands.setHardBreak(),
"Shift-Enter": () => this.editor.commands.addNewline(),
};
},
});
And used it like so;
editor = new Editor({
extensions: [
customNewline,
CustomHardBreak,
]
});
Use the default editor command createParagraphNear. E.g this.editor.commands.createParagraphNear()
I tried creating a custom extension from your code and ended up with something similar to the command above, i.e;
export const customNewline = Extension.create({
name: "newline",
priority: 1000, // Optional
addCommands() {
return {
addNewline:
() =>
({ state, dispatch }) => {
const { schema, tr } = state;
const paragraph = schema.nodes.paragraph;
const transaction = tr
.deleteSelection()
.replaceSelectionWith(paragraph.create(), true)
.scrollIntoView();
if (dispatch) dispatch(transaction);
return true;
},
};
},
addKeyboardShortcuts() {
return {
"Shift-Enter": () => this.editor.commands.addNewline(),
};
},
});
And added this as an extension in my editor instance.
PS:
They both work, almost exactly the same, I haven't found a difference yet. But there's somewhat of a 'catch' if you would call it that; Both these methods don't work on empty lines/nodes, a character has to be added before the cursor for it to work, any character, even a space.
In TipTap 2.0 I am able to use this custom extension:
const ShiftEnterCreateExtension = Extension.create({
addKeyboardShortcuts() {
return {
"Shift-Enter": ({ editor }) => {
editor.commands.enter();
return true;
},
};
},
});
To make shift + enter behave like enter.
In my case I actually wanted enter to do something different. So I use prosemirror events to set a ref flag on whether shift was pressed. Than I check that flag under the "Enter" keyboard event -- which could be triggered normally or through the shift + enter extension.

How to test a function that accepts a JSX.Element?

I have a type:
type button = JSX.Element | null;
and a function:
const getFirstButton = (buttonArray: button[], first: boolean) => {
if (first) {
return buttonArray[1];
}
return buttonArray.find(b => b !== null);
};
here is my test
test('getFirstButton', () => {
const buttons = // what goes here?
expect(getFirstButton(buttons, false)).toContain('button_1');
});
I need help with the second line on the test. How do i handle this?
Is this even possible?
Note: my test file is test.ts and I don't want to change it .tsx
JSX.Element is an object created by JSX syntax, i.e. React.createElement.
It can be:
const buttons = [null, null, <p/>, <div/>];
expect(getFirstButton(buttons, false)).toBe(buttons[2]);
Notice that JavaScript arrays are zero-based, so buttonArray[1] is possibly a mistake that will be detected when covering if (first) condition.

how to use shift on behaviorSubject?

I have a class with BehaviorSubject:
export class WordsService {
private words = new BehaviorSubject<WordType[]>([]);
It was fed with subscription:
init() {
this.databaseService.fetchWords().subscribe(
(listaWords: WordType[]) => {
this.words.next(listaWords);
},
errors => console.error('err'),
() => console.log('suceed')
)
}
And as I'm refactoring this code:
private fetchWord(): void{
this.word = this.wordService.getWords().shift();
}
I'm trying to get variable word to have data with .shift so it can take one element from observable at once, and when it will take all elements fetching's done.
It looks like you are trying to transform the results from a WordType[] to a single WordType.
You can do this by applying the map() operator like this:
init(){
this.databaseService.fetchWords().pipe(
map(words => words.shift())
)
.subscribe(
(listaWords: WordType[]) => {
this.words.next(listaWords);
},
errors => console.error('err'),
() => console.log('suceed')
)
}
However, you don't actually need a BehaviorSubject to do this, you can simply declare your observable directly from your service call:
public word: Observable<WordType> = this.databaseService.fetchWords().pipe(
map(words => words.shift()),
catchError(error => console.log(error))
);
Now, the word observable will only emit the value you are interested in.
This allows you to possibly use the async pipe in your template to manage the subscription and not need to do it yourself in the controller.
I would do it without shifting.
Imagine you have any observable value, for each emition of this observable value you want to pull a word. In my example this observable value is a page click.
Then you can do something like this:
const clicked$ = fromEvent(document, 'click');
const words$ = of(['AA', 'BB', 'CC', 'XX']);
const wordToPrint$ = zip(
clicked$,
words$.pipe(concatAll()),
).pipe(
map(([,word]) => word),
);
wordToPrint$.subscribe(console.log);
See stackblitz: https://stackblitz.com/edit/rxjs-ep1k3v?file=index.ts

Can you write a macro to invoke the default() operator in rust?

Something like:
macro_rules! default(
($T:ty, $($args:expr)*) => (
$T { $($args)*, ..Default::default() };
);
)
...but with a magical type instead of expr, so you could do something like:
let p = default!(CItem, _z: ~"Hi2", x: 10);
let q = default!(CItem, _z, ~"Hi2", x, 10);
let r = default!(CItem, { _z: ~"Hi2", x: 10 });
Or something along those lines?
Is there any macro symbol that simply picks up a literal block of characters without first parsing it as a type/expr/etc?
(I realize you'd typically just write a CItem::new(), but this seems like a nice situation in some circumstances)
Macros can have multiple pattern to match the syntax, so you have to write a seperate pattern for every case seperatly like this:
macro_rules! default(
($t:ident, $($n:ident, $v:expr),*) => {
$t { $($n: $v),*, ..Default::default() }
};
($t:ident, $($n:ident: $v:expr),*) => {
default!($t, $($n, $v),*)
};
)
As you can see there are two patterns, the first matching pairs seperated by comma and the second one pairs seperated by colon.

Performance issue : How to execute Two lambda expression at once?. "Contains" and "Any" operator used

Sample code
var Ids = _db.Projects.Where(Project=>Project.Title!="test23rdoct")
.Select (pro => pro.Id);
Expression<Func<Company, bool>> masterExpression =
Company => Company.Participants.Any(part => ids.Contains(part.Project.Id));
IQueryable<Object> queryEntity = _db.Companies.Where(masterExpression)
The above query executing twice. Storing ids in the server(sometime ids are more than 50k count). It causes performance issues. Could anybody suggest how to combine these two queries and execute at once?
How about:
var queryEntity = _db.Companies.Where(c => c.Partipants.Any(p => p.Project.Title != "test23rdoct"));
EDIT:
With the complex query, you could also split that:
Func<Project, bool> projectFilter = Project => ((Compare(Convert(Project.Title), "a") > 0) AndAlso ((Convert(Project.Title) != "test23rdoct") AndAlso
(Project.Participants.Any(Participant => (Compare(Convert(Participant.ParticipantRole.Name), "Finance") > 0)) AndAlso
(Project.Participants.Any(Participant => (Convert(Participant.Person.FirstName) != "test1")) AndAlso
Project.Participants.Any(Participant => (Compare(Convert(Participant.Company.Name), "test") > 0))))));
And then do:
var queryEntity = _db.Companies.Where(c => c.Partipants.Any(p => projectFilter(p.Project));
Would something like this using Join suit your needs?
Expression<Func<Company, bool>> masterExpression =
Company => Company.Participants.Join (Ids, p => p.Project.ID, id => id, (p, id) => p).Any();
IQueryable<Object> queryEntity = _db.Companies.Where(masterExpression);
I got this solution for avoiding execution of Lambda twice. To achieve this I used these extension methods Invoke() and AsExpandable(). Its available in Linqkit dll.
Expression<Func<Company, bool>> masterExpression = Company => Company.Participants.Any(part => masterLamba.Invoke(part.Project));
queryEntity = _db.Companies.AsExpandable().Where(masterExpression);

Resources