🎻 A collection of JavaScript+TypeScript design methods to inspire your coding.
I always ask myself the question "What is the best way of writing this code?" and so here is a collection of methods which you can use to help answer that question.
- Import a class as default.
import Inspo from 'inspiration';
- Import a class as a sub-module.
import { Inspo } from 'inspiration';
- Import a function as default.
import createInspiration from 'inspiration';
- Import a function as a sub-module.
import { createInspiration } from 'inspiration';
- Extend a class.
class Inspiration {
constructor(...args) {
// code...
}
doSomethingCool() {
// code...
}
}
export default class SuperInspiration extends Inspiration {
constructor(...args) {
super(args);
}
doSomethingElseThatIsCool() {
// code...
}
}
- Implement an interface.
interface Inspiration {
time: Date;
setTime(t: Date);
}
export default class SuperInspiration implements Inspiration {
time: Date;
setTime(t: Date) {
this.time = t;
}
}
- Use a static method to return an instance of a class.
class Inspiration {
static create(...args) {
return new Inspiration(...args);
}
name: string;
constructor(name: string) {
this.name = name;
}
}
export default Inspiration.create('coolName');
- Create a custom function.
export default function MyCoolFunction() {
// code...
}
Or...
export default () => {
// code...
}
- Use a pre-made function.
function createInspiration(name: string, time: number, ...args: any[]) {
return `${name} ${time}`;
}
export default createInspiration('coolName', 12345);
- Use a function with a parameter bag.
function createInspiration({ name, time, ...args }) {
return `${name} ${time}`;
}
export default createInspiration({
name: 'coolName',
time: 12345,
});
- Use a function with string literals.
function createInspiration(stringParts: string[], ...stringExpressions: any[]) {
// code...
}
const color = 'green';
export default createInspiration`
backgroundColor: ${color};
`;
- Use in a class.
export default class Inspiration {
constructor(
private name: string = 'coolName'
) {}
get uppercaseName() {
return this.name.toUpperCase();
}
set uppercaseName(updatedName: string) {
this.name = updatedName;
}
}
- Use in a Proxy.
function createInspirationProxy() {
const initialTarget = {
name: 'coolName',
};
const handler = {
get(target, property) {
if (!target[property]) {
throw new Error(`Property "${property}" does not exist on proxy target.`);
}
return target[property];
},
set(target, property, value) {
target[property] = `${value}Name`;
},
};
return new Proxy(initialTarget, handler);
}
const exampleProxy = createInspirationProxy();
console.log(exampleProxy.name); // "coolName"
console.log(exampleProxy.doesNotExist); // throws error
exampleProxy.name = 'blah';
console.log(exampleProxy.name); // "blahName"
- Jack Scott @jacrobsco - I tweet about coding and startups.