Skip to content

Instantly share code, notes, and snippets.

@justaguywhocodes
Created September 26, 2021 04:34
Show Gist options
  • Save justaguywhocodes/415934f3fa73daebfc823ec79a41c109 to your computer and use it in GitHub Desktop.
Save justaguywhocodes/415934f3fa73daebfc823ec79a41c109 to your computer and use it in GitHub Desktop.
Convert LeetCode ePub to JSON format
import cheerio from 'cheerio';
import fs from 'fs';
import { globby } from 'globby';
const main = async() => {
const paths = await globby(['EPUB/*', '!cake']);
let results = [];
paths.forEach((path) => {
const data = fs.readFileSync(path, { encoding: 'utf8', flag: 'r' });
const $ = cheerio.load(data);
let match = /^(\d{1,4})/.exec($('div#title').text());
// const qMatch = /^(.+)/.exec($(".content__u3I1").childNodes[1].text());
results.push({
id: match && match[0] ? String(match[0]) : 'na',
title: $('div#title').text().replace(/^\d+\./, "").trim(),
question: $(".content__u3I1 > div > p").filter((el) => !/Example/.test(el.toString())).text().replace(/Example \d:/g, "").replace(/Constraints:/g, "").replace(/\./g, ".\n").trim(),
examples: $("pre").text().split("\n"),
constraints: $("ul > li").text().split(","),
});
});
fs.writeFileSync('data.json', JSON.stringify(results));
};
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment