db-country
Version:
In-memory countries' database
83 lines (74 loc) • 3.03 kB
JavaScript
((api,m,rq)=>{
((ETL,JFile)=>{
api.db={};
api.db.meta={};
api.db.meta.cols_countries=['name_en','name_de','name_local','code','continent','capital','population',
'area','coastline','gov','currency','currency_code','dialing_prefix','birthrate',
'deathrate','life_expect','url'];
api.db.countries=ETL.extract(`${__dirname}/db/countries.csv`,{
delimitor:';',
ignore:(line,index)=>index>=1 && line.length>10,
headers:api.db.meta.cols_countries}).map((e)=>{
let ee=e;
Object.keys(e).forEach((k)=>ee[k]=e[k].replace('"','').replace('"',''))
return ee;
});
class _{
constructor(o){
Object.keys(o).forEach((p)=>this[p]=o[p]);
}
static groupBy(p){
return api.db.countries.groupBy(p);
};
toString(){
return JSON.stringify(this);
}
persist(file,append){
file=new JFile(file);
(append)?file.text+=`\n${this.toString()}`:file.text=this.toString();
}
static size(){
return api.db.countries.length;
}
static get(id){
return (isFinite(id)?api.db.countries[id-1]:this.findBy('name_en',id)[0])
}
static from(db){
return db.map((o)=>new this(o));
};
static findBy(p,v){
if(p==='name'){p='name_en'}
if(p=='name_en'&&v.toLowerCase()==='israel'){v="Palestine"};
return api.db.countries.filter((c)=>(isFinite(c[p])?parseInt(c[p])===v:c[p].toLowerCase() ===v.toLowerCase()));
};
static find(f){
return api.db.countries.filter((e,i)=>f(e,i,api.db.meta.cols_countries));
};
static findGE(p,v){
return api.db.countries.filter((c)=>(isFinite(c[p])?parseFloat(c[p])>=v:c[p].toLowerCase() ===v.toLowerCase()));
}
static findLE(p,v){
return api.db.countries.filter((c)=>(isFinite(c[p])?parseFloat(c[p])<=v:c[p].toLowerCase() ===v.toLowerCase()));
}
static findAround(p,min,max){
return api.db.countries.filter((c)=>(isFinite(c[p])?parseFloat(c[p])>=min && parseFloat(c[p])<=max :c[p].toLowerCase() ===v.toLowerCase()));
}
static findAll(){
return api.db.countries;
};
static persist(file,append){
file=new JFile(file),content=this.from(api.db.countries).map((c)=>c.toString()).join('\n');
(append)?file.text+=`\n${content}`:file.text=content;
return api.db.countries;
}
static capital(name){
try {
return this.findBy('name_en',name)[0].capital;
} catch (e) {
console.log(new Date(),`: Country with name "${name}" is NOT FOUND!`);
}
}
}
m.exports=_;
})(rq('node-etl'),rq('jfile'))
})({},module,require)