So I have some Javascript code that resembles the following:
var mylibrary = new (function ()
{
this._getLibraryObj = function ()
{
var newLibraryObj = {};
var libraryData = window.specifiedLibraryData;
// Add head librarian details
// open library
// etc. etc. turn into an object from data
return newLibraryObj ;
};
this.item = function (item)
{
if (this.obj && item in this.obj)
{
return this.obj[item];
}
else
{
this.obj = this._getLibraryObj();
if (item in this.obj)
{
return this.obj[item];
}
return null;
}
};
return this;
})();
What annoys me is that this.item(item)
function repeats the item in this.obj[item]
and I find it a little hard to read. I was hoping for it to not have to run _getLibraryObj
too often.
Question: How would you rewrite this.item()
to be short and sweet (DRY and readable)?
EDIT:- From alex's post I realised I left out one constraint: If the item isn't in the library object then it might need to _getLibraryObj()
again as the data may have changed
Solution:- I ended up using @Alex Nolan's fifth example (with ||
instead of &&
I find it easier to read.):
this.item = function(item)
{
if(!this.obj || !item in this.obj)
{
this.obj = this._getLibraryObj();
}
return this.obj[item] || null;
}