class RegexRemover extends Command {
constructor(protected regex: RegExp) {
super();
}
execute(text: string): string {
return text.replace(this.regex, '');
}
}
class RemoveExtraWhitespaces extends RegexRemover {
constructor() {
super(/\s\s+/g);
}
}
const remover = new RemoveExtraWhitespaces();
const clean = remover.execute(
'The dog has a long tail, and it is RED!',
);
console.log(clean);
// prints 'The dog has a long tail, and it is RED!'
abstract class Command {
abstract execute(text: string): string;
}
let text = 'The dog has a long tail, and it @ is RED!'
const commands: Commands[] = [];
commands.push(new RemoveWhitespaces());
commands.push(new RemoveInvalid());
for(const command of commands){
text = command.execute(text);
}
console.log(text);
// The dog has a long tail, and it is RED!
interface / base class
derived classes
iteration & use common interface
Animal
Vehicle
is-a
implements ridable
Ridable
abstract class Command {
abstract execute(text: string): string;
}
interface Hookable {
onRead?: (text: string) => string;
onProcess?: (text: string) => string;
onWrite?: (text: string) => void;
}
class RemoveExtraWhitespaces
extends Command
implements Hookable {
execute(text: string): string {
const regex = new RegExp(/\s\s+/g);
return text.replace(regex, '');
}
onProcess(text: string): string {
return text.toUpperCase();
}
}
class MySqlWriter
extends Writer
implements Hookable {
protected client: MySqlClient;
constructor(conn: MySqlConnection,
protected tableName: string) {
this.client = new MySqlClient(con)
}
write(text: string) {
this.client.write(this.tableName, text);
}
onWrite(text: string): void {
this.logger.log('Wrote to ES')
}
}
abstract class Writer {
abstract write(text: string): void;
}
class RemoveExtraWhitespaces
extends Command {
execute(text: string): string {
const regex = new RegExp(/\s\s+/g);
return text.replace(regex, '');
}
}
class MySqlWriter
extends Writer {
protected client: MySqlClient;
constructor(conn: MySqlConnection,
protected tableName: string) {
this.client = new MySqlClient(con)
}
write(text: string) {
this.client.write(this.tableName, text);
}
}
const commands: Commands[] = [];
commands.push(new RemoveWhitespaces());
commands.push(new RemoveInvalid());
commands.push(new EsWriter());
const reader: Reader = new MySqlReader();
const stream = reader.stream();
stream.read('data', text => {
for(const command of commands){
if(command.onProcess) {
text = command.onProcess(text);
}
text = command.execute(text);
if(command.onWrite) {
command.onWrite();
}
}
})
Custom Hooks, if exists