Passed
Push — master ( eab35c...1d0b42 )
by Endre
01:10 queued 14s
created

src/Registry.ts   A

Complexity

Total Complexity 9
Complexity/F 1.8

Size

Lines of Code 65
Function Count 5

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 50
dl 0
loc 65
ccs 22
cts 22
cp 1
rs 10
c 0
b 0
f 0
wmc 9
mnd 4
bc 4
fnc 5
bpm 0.8
cpm 1.8
noi 0
1
import ListenerAdapter from '@enbock/state-value-observer/ListenerAdapter';
2
import {IObserver} from '@enbock/state-value-observer/Observer';
3
import {IPageData} from './Router';
4
5
export interface IPageDictionary<T> {
6
  [index: string]: T
7
}
8
9
export default class Registry {
10
  dictionary: IPageDictionary<IPageData>;
11
  observer: IObserver<IPageData | null>;
12
13
  constructor(observer: IObserver<IPageData | null>) {
14 4
    this.observer = observer;
15 4
    this.dictionary = {};
16
  }
17
18
  attachAdapter(adapter: ListenerAdapter<IPageData | null>): void {
19 2
    adapter.addListener(this.updatePageData.bind(this));
20
  }
21
22
  getPages(): IPageData[] {
23 2
    const pages: IPageData[] = [];
24
25 2
    Object.keys(this.dictionary).forEach((pageName: string) => {
26 2
      const page: IPageData = this.dictionary[pageName];
27 2
      pages.push(page);
28
    });
29
30 2
    return pages;
31
  }
32
33
  registerPage(page: IPageData) {
34 6
    if (this.observer.value != null) {
35 5
      this.updatePageUrlByDepth(this.observer.value, page);
36
    }
37 6
    this.dictionary[page.name] = page;
38
  }
39
40
  protected updatePageData(newValue: IPageData | null): void {
41 3
    if (newValue == null) return;
42 2
    Object.keys(this.dictionary).forEach(
43
      (pageName: string) => {
44 6
        this.updatePageUrlByDepth(newValue, this.dictionary[pageName]);
45
      }
46
    );
47
  }
48
49
  protected updatePageUrlByDepth(currentPage:IPageData, registeredPage: IPageData): void {
50 11
    let relativeBack: string = '', index: number = 0, newUrl: string;
51
52 11
    if (registeredPage == currentPage) {
53 4
      newUrl = registeredPage.baseUrl.replace(/.*\//, './');
54
    } else {
55 7
      const depth: number = currentPage.baseUrl.replace(/[^\/]*/g, '').length - 1;
56 7
      for (index = 0; index < depth; index++) {
57 13
        relativeBack += '../';
58
      }
59 7
      newUrl = (relativeBack + registeredPage.baseUrl).replace('.././', '../');
60
    }
61
62 11
    registeredPage.currentUrl = newUrl;
63
  }
64
}
65