0
\$\begingroup\$

I am required to create a bunch of object nodes to an object:

this.selectedText = e.text;
this.clipNo = e.clipNo;

if(!this.clipCollection.hasOwnProperty(this.category)) {
    this.clipCollection[this.category] = {};
}

if(!this.clipCollection.hasOwnProperty("grandClipCount")) {
    this.clipCollection.grandClipCount = 0;
}

if(!this.clipCollection[this.category].hasOwnProperty(['pageNo'+this.pageNumber])) {
    this.clipCollection[this.category]['pageNo'+this.pageNumber] = {};
    this.clipCollection[this.category]['pageNo'+this.pageNumber].pageServerInfo = this.pageServerInfo;
}

if(!this.clipCollection[this.category][this.category+"ClipCount"]) {
    this.clipCollection[this.category][this.category+"ClipCount"] = 0;
}

if(!this.clipCollection[this.category]['pageNo'+this.pageNumber].hasOwnProperty("clips")) {
    this.clipCollection[this.category]['pageNo'+this.pageNumber].clips = {};
    this.clipCollection[this.category]['pageNo'+this.pageNumber].clips['clip'+this.clipNo] = this.selectedText;
    this.clipCollection[this.category]['pageNo'+this.pageNumber].pageClipCount = 0;
}

this.clipCollection[this.category]['pageNo'+this.pageNumber].clips['clip'+this.clipNo] = this.selectedText;
this.clipCollection[this.category]['pageNo'+this.pageNumber].pageClipCount += 1;
this.clipCollection[this.category][this.category+"ClipCount"] += 1;
this.clipCollection.grandClipCount += 1;

Is there a short approach to minimize this code?

\$\endgroup\$
2
\$\begingroup\$

Well for starters maybe get rid of this with a few local variables and give names to often used constants, e.g.

var pageNo = 'pageNo'+this.pageNumber;

or so.

The blocks with hasOwnProperty checks can be replaced with a conditional:

this.clipCollection[this.category] = this.clipCollection[this.category] || {};

this.clipCollection.grandClipCount = (this.clipCollection.grandClipCount || 0) + 1;

And so on.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.