Skip to content

Commit

Permalink
refactor: redesign createStoreInstanceId name logic
Browse files Browse the repository at this point in the history
  • Loading branch information
zhxttkx authored and why520crazy committed Dec 19, 2023
1 parent 3989c95 commit ca04079
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
7 changes: 7 additions & 0 deletions packages/store/internals/internal-store-factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import { newWeakRef, WeakRef } from '../weak-ref';
export class InternalStoreFactory implements OnDestroy {
private static factory: InternalStoreFactory;

private currentId: number = 0;

static get instance() {
if (!this.factory) {
this.factory = new InternalStoreFactory();
Expand All @@ -19,6 +21,11 @@ export class InternalStoreFactory implements OnDestroy {

public state$ = new Subject<{ storeId: string; state: unknown }>();

generateId(): number {
this.currentId += 1;
return this.currentId;
}

register(store: Store) {
this.storeInstancesMap.set(store.getStoreInstanceId(), newWeakRef(store));
}
Expand Down
29 changes: 15 additions & 14 deletions packages/store/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,23 +211,24 @@ export class Store<T = unknown> implements Observer<T>, OnDestroy {
}

private createStoreInstanceId(): string {
const instanceMaxCount = this.getInstanceMaxCount();
const name = this.getName();
if (!InternalStoreFactory.instance.get(name)) {
return name;
}
let j = 0;
for (let i = 1; i <= instanceMaxCount - 1; i++) {
if (!InternalStoreFactory.instance.get(`${name}-${i}`)) {
j = i;
break;
const id = InternalStoreFactory.instance.generateId();
if (isDevMode()) {
const instanceMaxCount = this.getInstanceMaxCount();
let count = 1;
for (let i = 1; i < id; i++) {
if (InternalStoreFactory.instance.get(`${name}-${i}`)) {
count++;
if (count > instanceMaxCount) {
break;
}
}
}
if (count > instanceMaxCount) {
throw new Error(`store '${name}' created more than ${instanceMaxCount}, please check it.`);
}
}

if (j === 0 && isDevMode()) {
throw new Error(`store '${name}' created more than ${instanceMaxCount}, please check it.`);
}
return `${name}-${j}`;
return `${name}-${id}`;
}

private getInstanceMaxCount() {
Expand Down

0 comments on commit ca04079

Please sign in to comment.