Skip to content

Instantly share code, notes, and snippets.

@akash-joshi
Created July 1, 2019 12:07
Show Gist options
  • Save akash-joshi/476ead410a244a48e037c138ba2387b0 to your computer and use it in GitHub Desktop.
Save akash-joshi/476ead410a244a48e037c138ba2387b0 to your computer and use it in GitHub Desktop.
// This API needs to be deployed to a server or serverless backend.
// I used now.sh to deploy it. You can find a tutorial here : https://zeit.co/docs/v2/deployments/basics/
const { parse } = require('url');
const axios = require('axios');
module.exports = async (req, res) => {
function similarity(s1, s2) {
var longer = s1;
var shorter = s2;
if (s1.length < s2.length) {
longer = s2;
shorter = s1;
}
var longerLength = longer.length;
if (longerLength == 0) {
return 1.0;
}
return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength);
}
function editDistance(s1, s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
var costs = new Array();
for (var i = 0; i <= s1.length; i++) {
var lastValue = i;
for (var j = 0; j <= s2.length; j++) {
if (i == 0)
costs[j] = j;
else {
if (j > 0) {
var newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue),
costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length] = lastValue;
}
return costs[s2.length];
}
const { query } = parse(req.url, true)
const { hero = 'World' } = query;
const resp = await axios.get('https://akabab.github.io/superhero-api/api/all.json');
let foundData;
resp.data.map( elem => {
if((similarity(hero,elem.name)>=.8 || similarity(hero,elem.biography.fullName)>=.8) && !foundData) {
foundData = elem;
}
});
foundData ? res.end(JSON.stringify(foundData)) : res.end('Hero Not Found');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment