Last active
August 22, 2021 20:03
-
-
Save zetavg/2d5d782ba4b8849f9af639708e011fb5 to your computer and use it in GitHub Desktop.
API wrapper of https://dictionary-api.cambridge.org/
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
async function lookup(word, dictionaryCode = 'american-english', accessKey = window.ACCESS_KEY) { | |
const response = await fetch( | |
`https://dictionary.cambridge.org/api/v1/dictionaries/${dictionaryCode}/search/first/?q=${word}&format=xml`, | |
{ | |
method: 'GET', | |
headers: { accessKey }, | |
} | |
); | |
const json = await response.json(); | |
const parser = new DOMParser(); | |
const entryContentDom = parser.parseFromString(json.entryContent, 'application/xml'); | |
const entryContent = xml2json(entryContentDom); | |
lookup.debug_entryContent = entryContent; | |
const definitions = possibleArray(entryContent.di['pos-block']).flatMap((posBlock) => { | |
const pos = posBlock.header.info.posgram.pos; | |
return possibleArray(posBlock['sense-block']) | |
.flatMap((senseBlock) => possibleArray(senseBlock['def-block'])) | |
.filter((defBlock) => typeof defBlock.definition.def === 'string') | |
.map((defBlock) => { | |
return { | |
pos, | |
definition: defBlock.definition.def.replace(/: *$/, ''), | |
examples: possibleArray(defBlock.examp).filter((ex) => ex).map((ex) => ex.eg), | |
}; | |
}); | |
}); | |
return { | |
word: possibleArray(entryContent.di.header)[0].title, | |
definitions, | |
}; | |
} | |
function contentToCard(content) { | |
return content.word + '\n---\n' + content.definitions.map((d) => ( | |
d.definition + (d.examples && d.examples.length > 0 && `:\n${d.examples.map((exp) => `💬 ${exp}`).join('\n')}`) || '' | |
)).join('\n-\n') + '\n===\n'; | |
} | |
async function getCardFromWords(words) { | |
const defs = await Promise.all(words.map(w => lookup(w))); | |
return defs.map(c => contentToCard(c)).join(''); | |
} | |
function possibleArray(arr) { | |
return Array.isArray(arr) ? arr : [arr] | |
} | |
function xml2json(xml) { | |
var obj = {}; | |
if (xml.children.length > 0) { | |
for (var i = 0; i < xml.children.length; i++) { | |
var item = xml.children.item(i); | |
var nodeName = item.nodeName; | |
if (typeof (obj[nodeName]) == "undefined") { | |
obj[nodeName] = xml2json(item); | |
} else { | |
if (typeof (obj[nodeName].push) == "undefined") { | |
var old = obj[nodeName]; | |
obj[nodeName] = []; | |
obj[nodeName].push(old); | |
} | |
obj[nodeName].push(xml2json(item)); | |
} | |
} | |
} else { | |
obj = xml.textContent; | |
} | |
return obj; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment