From c143fee84999850f821fa7f4ea4950fc77e1a38b Mon Sep 17 00:00:00 2001 From: Connor Wyatt Date: Fri, 30 Sep 2016 17:42:54 +0100 Subject: [PATCH] refactor(routerLinkActive): optimised routerLinkActive active check code (#11968) Modify routerLinkActive to optimise performance by removing unnecessary iteration. By replacing Array.reduce with Array.some, the loop will break when it finds an active link. Useful if used on the parent of a large group of routerLinks. Furthermore, if a RouterLink is active it will not check the RouterLinkWithHrefs. --- .../src/directives/router_link_active.ts | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/modules/@angular/router/src/directives/router_link_active.ts b/modules/@angular/router/src/directives/router_link_active.ts index e41c259f4d..49867f5150 100644 --- a/modules/@angular/router/src/directives/router_link_active.ts +++ b/modules/@angular/router/src/directives/router_link_active.ts @@ -109,17 +109,18 @@ export class RouterLinkActive implements OnChanges, OnDestroy, AfterContentInit private update(): void { if (!this.links || !this.linksWithHrefs || !this.router.navigated) return; - const isActiveLinks = this.reduceList(this.links); - const isActiveLinksWithHrefs = this.reduceList(this.linksWithHrefs); + const isActive = this.hasActiveLink(); this.classes.forEach( - c => this.renderer.setElementClass( - this.element.nativeElement, c, isActiveLinks || isActiveLinksWithHrefs)); + c => this.renderer.setElementClass(this.element.nativeElement, c, isActive)); } - private reduceList(q: QueryList): boolean { - return q.reduce( - (res: boolean, link: any) => - res || this.router.isActive(link.urlTree, this.routerLinkActiveOptions.exact), - false); + private isLinkActive(router: Router): (link: (RouterLink|RouterLinkWithHref)) => boolean { + return (link: RouterLink | RouterLinkWithHref) => + router.isActive(link.urlTree, this.routerLinkActiveOptions.exact); + } + + private hasActiveLink(): boolean { + return this.links.some(this.isLinkActive(this.router)) || + this.linksWithHrefs.some(this.isLinkActive(this.router)); } }