Skip to content

Instantly share code, notes, and snippets.

@jednano
Last active January 23, 2019 23:41
Show Gist options
  • Save jednano/99d590dad86dc2effd0d57cbde59240c to your computer and use it in GitHub Desktop.
Save jednano/99d590dad86dc2effd0d57cbde59240c to your computer and use it in GitHub Desktop.
transpile
import transpile, { Writer } from './transpile';
describe('transpile', () => {
describe('given a reader that always reads "foobarbaz"', () => {
const reader = { read: () => 'foobarbaz' };
describe('given a default writer', () => {
const writer = new Writer();
it('sequentially applies 2 mods and returns expected result as a string', () => {
const result = transpile(
reader,
[
x => x.replace('foo', 'qux'),
x => x.replace('xbar', 'thud'),
],
writer,
);
expect(result).toEqual('quthudbaz');
});
});
describe('given a writer that is configured to write JSON', () => {
const writer = new Writer('json');
it('sequentially applies 2 mods and returns expected result as JSON', () => {
const result = transpile(
reader,
[
x => x.replace('foo', 'qux'),
x => x.replace('xbar', 'thud'),
],
writer,
);
expect(JSON.parse(result)).toEqual('quthudbaz');
});
});
});
});
export interface Reader {
read(): string;
}
export class Writer {
constructor(private format?: 'json' | string) {}
public write(value: string) {
return this.format === 'json' ? JSON.stringify(value) : value;
}
}
export type Mod = (value: string) => string;
export default function transpile(
reader: Reader,
mods: Mod[],
writer: Writer,
) {
let text = reader.read();
mods.forEach(mod => {
text = mod(text);
});
return writer.write(text);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment