UNPKG

wordfind

Version:

Unofficial API for wordfind.com

35 lines (30 loc) 1.66 kB
/* WordFind.com | Unofficial API to query http://wordfind.com/ */ let xhr = require('mu.js') /* my package that requests and initializes jQuery on remote document */ var WordFind = new class WordFind { /* */ }() let methods = ['starts-with', 'ends-with', 'contains'] /* supported methods by wordfind.com */ /* the method argument prevents duplicate code for startsWith, endsWith, contains */ WordFind.query = (method, what) => new Promise((deliver, renege) => { if(methods.indexOf(method) != -1) { /* array methods has method argument */ xhr(`https://wordfind.com/${method}/${what}`).then($ => { /* store results in array data */ let data = [] /* find and iterate all elements with class="defLink" (<li>) */ $('.defLink').each(function() { let a = $('a', $(this)) /* <a> element inside this element */ let href = a.attr('href') /* href attribute of this link */ if(href.indexOf('/word/') != -1) { // href contains '/word/' so is link to a word let word = href.split('/word/')[1].replace(/\//g, '') // replace all '/' symbols with nothing if(word != what) /* not a link to word being queried */ data.push(word) } }) deliver(data) /* resolve this Promise */ }).catch(renege) /* reject errors of xhr */ } else renege(new Error(`Method '${method}' not supported`)) /* unknown method, reject promise */ }) /* wrapping query function to named methods */ WordFind.startsWith = what => WordFind.query('starts-with', what) WordFind.endsWith = what => WordFind.query('ends-with', what) WordFind.contains = what => WordFind.query('contains', what) module.exports = WordFind