Skip to content

Instantly share code, notes, and snippets.

@nikaspran
Last active February 6, 2019 08:30
Show Gist options
  • Save nikaspran/c340716ea882f5b5503c14c5604bcf94 to your computer and use it in GitHub Desktop.
Save nikaspran/c340716ea882f5b5503c14c5604bcf94 to your computer and use it in GitHub Desktop.
JS Quick Tips

JS Quick Tips

This is a collection of quick and helpful JS tips or code snippets that might be useful in various circumstances.

function assertRequired(params) {
Object.keys(params).forEach((key) => {
if (params[key] === undefined) {
throw new Error(`${key} is required`);
}
});
};
function someFunction({ requiredArg, optionalArg }) {
assertRequired({ requiredArg });
return 'ok';
}
someFunction({}); // Error: requiredArg is required
someFunction({ requiredArg: 1 }); // ok
async function buildUser(user = {}) {
return db.User.create(user);
}
async function buildRole({ user, ...role } = {}) {
return db.Role.create({
userId: (user || await buildUser()).id,
...role,
});
}
const user = await buildUser({ name: 'Test' });
await buildRole({ user }); // use custom value
await buildRole(); // use the async default
// Prefer explicit checks for features over hardcoded environment dependencies
// explicit checks make it easier to compose and change feature sets on the fly
// i.e. if you want to add new QA environments, unit tests or even disable something quickly
// avoid
if (process.env.NODE_ENV === 'production') { // hardcoded
sendEmails();
}
// do
if (process.env.ENABLE_SENDING_EMAILS) { // explicit
sendEmails();
}
async function sendEmail(templateName, data) {
if (process.env.SHOULD_SEND_EMAIL) {
const renderedEmail = await templates.render(templateName, {
renderedAt: new Date(),
...data,
});
// more code?
await emails.send(renderedEmail);
}
}
// with guard clause:
async function sendEmail(templateName, data) {
if (!process.env.SHOULD_SEND_EMAIL) {
return;
}
const renderedEmail = await templates.render(templateName, {
renderedAt: new Date(),
...data,
});
// more code?
await emails.send(renderedEmail);
}
function symbolFor(currency) {
if (currency === 'EUR') {
return '€';
} else if (currency === 'USD') {
return '$';
} else {
return currency;
}
}
// vs
const symbolForCurrency = { // data over logic, so easier to add more and simpler to understand
EUR: '€',
USD: '$',
}
const symbolFor = currency => symbolForCurrency[currency] || currency;
it('should work', () => {
expect(onPress).toBeCalledWith(expect.objectContaining({
x: expect.any(Number),
y: expect.any(Number),
}));
});
// vs
const { objectContaining, any } = expect;
it('should work', () => {
expect(onPress).toBeCalledWith(objectContaining({
x: any(Number),
y: any(Number),
}));
});
// Since often have to switch between React.Component and a functional one or introduce React.Fragment temporarily
// Importing React only helps avoid extra diff lines
import React, { Fragment } from 'react';
const Header = () => (
<Fragment>
Hello World
</Fragment>
);
import React from 'react';
const Header = () => (
<div>
Hello World
</div>
);
// vs
import React from 'react';
const Header = () => (
<React.Fragment>
Hello World
</React.Fragment>
);
import React from 'react';
const Header = () => (
<div>
Hello World
</div>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment