Last active
January 23, 2019 23:41
-
-
Save jednano/99d590dad86dc2effd0d57cbde59240c to your computer and use it in GitHub Desktop.
transpile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'); | |
}); | |
}); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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