I do not know if it's possible but I would factorize functions like
// wiki
if(command === "wiki"){
bangSearch('wikiSearch','_',args);
}
// afr amazon fr
if(command === ("afr")){
bangSearch('amazonSearch','+',args);
}
function wikiSearch(recherche){
var url = "https://fr.wikipedia.org/w/api.php?action=opensearch&search="+recherche+"&limit=1&namespace=0&format=json";
request(url, function(err, resopnse, json){
//some code
});
}
function amazonSearch(recherche){
var url = "https://www.amazon.fr/s/ref=nb_sb_noss?__mk_fr_FR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&url=search-alias%3Daps&field-keywords="+recherche;
message.channel.send('Recherche amazon pour: '+recherche+'\n'+url);
}
function bangSearch(searchFunctionName,keywordSeparator,args){
if(args.length > 1){
searchFunctionName(args.join(keywordSeparator));
}else if (args.length == 0) {
searchFunctionName(/*some args*/);
}else{
searchFunctionName(args[0]);
}
}
But when i run the code, I have this error: TypeError: searchFunctionName is not a function
So, I understand that the code does not call searchFunctionName like wikiSearch or amazonSearch but it only understands that the called function is searchFunctionName.
So I can not call the argument function which is either "wikiSearch" or "amazonSearch"
Is it possible to do this? Can you help me ?
The entire code: Here is the entire code. It's for a discord bot and i use Discord.js
// wiki
if(command === "wiki"){
console.log(args);
bangSearch(wikiSearch,'_',args);
}
// afr amazon fr
if(command === ("afr")){
bangSearch(amazonSearch,'+',args);
}
function wikiSearch(recherche){
var url = "https://fr.wikipedia.org/w/api.php?action=opensearch&search="+recherche+"&limit=1&namespace=0&format=json";
request(url, function(err, resopnse, json){
try {
var name = JSON.parse(json)[1];
var link = JSON.parse(json)[3];
if(name ==='undefined'){
message.channel.send('Aucun résultats');
}else {
message.channel.send('Recherche wikipedia pour: '+recherche);
message.channel.send('Nom: '+name[0]+'\n'+link[0]+'\n\n');
}
} catch (e) {
callback('ERREUR: '+e);
}
});
}
function amazonSearch(recherche){
var url = "https://www.amazon.fr/s/ref=nb_sb_noss?__mk_fr_FR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&url=search-alias%3Daps&field-keywords="+recherche;
message.channel.send('Recherche amazon pour: '+recherche+'\n'+url);
}
function bangSearch(searchFunctionName,keywordSeparator,args){
if(args.length > 1){
searchFunctionName(args.join(keywordSeparator));
}else if (args.length == 0) {
message.channel.send('tu veux quoi ?').then(() => {
message.channel.awaitMessages(response => response.content.length > 0 , {
max: 1,
time: 10000,
errors: ['time'],
}).then((collected) => {
searchFunctionName(collected.first().content);
}).catch(() => {
message.channel.send('T\'as pas trouvé les touches sur ton clavier ou quoi ?');
});
});
}else{
searchFunctionName(args[0]);
}
}