I have two methods getTargetComponentById and getTargetComponentByName which perform a lookup on an object based on a particular key and returns an object. The two methods work fine seperated, but I would like to combine them to cut down on duplicated code. What would be the best way of combining them:
getTargetComponentById(componentId: string): IComponentTarget[] {
const targetComponents = [];
const website = this.website.getValue();
for (let i = 0; i < website.pages.length; i++) {
for (let j = 0; j < website.pages[i].components.length; j++) {
if (website.pages[i].components[j].componentId === componentId) {
targetComponents.push({
activePageIndex: i,
activeComponentIndex: j,
});
}
}
}
return targetComponents;
}
getTargetComponentByName(componentName: string, activeWebsite = null): IComponentTarget[] {
let website: IWebsite;
if (activeWebsite === null) {
website = this.website.getValue();
} else {
website = activeWebsite;
}
const targetComponents = [];
for (let i = 0; i < website.pages.length; i++) {
for (let j = 0; j < website.pages[i].components.length; j++) {
if (website.pages[i].components[j].componentName === componentName) {
targetComponents.push({
activePageIndex: i,
activeComponentIndex: j,
});
}
}
}
return targetComponents;
}
getTargetComponentById(componentId: string, activeWebsite = null),const website = activeWebsite || this.website.getValue();, then you only have to find a way how to distinguish an id from a name.