forked from elsys/fp-haskell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract.js
53 lines (39 loc) · 1.29 KB
/
extract.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const fs = require('fs');
function fail(msg) {
console.error(msg || 'Snap! I failed!');
process.exit(1);
}
function partition(arr, predicate) {
return [ arr.filter(predicate), arr.filter(x => !predicate(x)) ];
}
const [flags, args] = partition(process.argv.slice(2), x => /^--/.test(x));
const withTests = flags.indexOf('--tests') !== -1;
const fileName = args[0];
fs.existsSync(fileName) || fail(`File "${fileName}" does not exist!`);
const contents = fs.readFileSync(fileName, "utf-8");
const parts = [];
contents.replace(/```hs((?:.|\n)*?)```/g, (_, part) => parts.push(part));
const tests = [];
const hsSrc = parts
.filter(val => /^\s*/.exec(val)[0].length < 5)
.map(val => val.replace(/\s*--.*/g, ''))
.map(val => val.replace(/^> *(.*)\n(.*)\n/gm, (_, expr, res) => {
tests.push([expr, res]);
return '';
}))
.join('')
.replace(/\n{3,}/g, '\n\n');
const main = `
main :: IO ()
main = putStrLn $ printRes testAll
where printRes True = "Success!"
`;
const testAll = `
testAll :: Bool
testAll = ${tests
.map(([expr, res]) => `(${expr}) == ${res} || error ${JSON.stringify(expr + ' == ' + res)}`)
.join('\n && ')
}
`;
console.log(withTests ? hsSrc + main + testAll
: hsSrc);