Skip to content

Commit

Permalink
refactor: make wait optional
Browse files Browse the repository at this point in the history
  • Loading branch information
StyleShit committed Feb 13, 2025
1 parent 71d0603 commit b936a37
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 10 deletions.
24 changes: 17 additions & 7 deletions src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ describe('Synctactic', () => {
const { unSync } = sync({
subscribe: (cb) => eventEmitter.subscribe(cb),
syncFn,
wait: 100,
options: {
wait: 100,
},
});

// Assert.
Expand Down Expand Up @@ -58,7 +60,9 @@ describe('Synctactic', () => {
const { unSync } = sync({
subscribe: (cb) => eventEmitter.subscribe(cb),
syncFn,
wait: 100,
options: {
wait: 100,
},
});

// Act - Initiate a first sync.
Expand Down Expand Up @@ -88,8 +92,8 @@ describe('Synctactic', () => {
const { unSync } = sync({
subscribe: (cb) => eventEmitter.subscribe(cb),
syncFn,
wait: 100,
options: {
wait: 100,
notifyOnLeave: true,
},
});
Expand Down Expand Up @@ -122,8 +126,8 @@ describe('Synctactic', () => {
const { unSync } = sync({
subscribe: (cb) => eventEmitter.subscribe(cb),
syncFn,
wait: 100,
options: {
wait: 100,
notifyOnLeave: true,
},
});
Expand Down Expand Up @@ -156,7 +160,9 @@ describe('Synctactic', () => {
const { unSync } = sync({
subscribe: (cb) => eventEmitter.subscribe(cb),
syncFn,
wait: 100,
options: {
wait: 100,
},
});

// Act.
Expand All @@ -177,7 +183,9 @@ describe('Synctactic', () => {
const { unSync } = sync({
subscribe: (cb) => eventEmitter.subscribe(cb),
syncFn,
wait: 100,
options: {
wait: 100,
},
});

// Act - Initiate a sync.
Expand All @@ -199,7 +207,9 @@ describe('Synctactic', () => {
const { forceSync, unSync } = sync({
subscribe: (cb) => eventEmitter.subscribe(cb),
syncFn,
wait: 100,
options: {
wait: 100,
},
});

// Act.
Expand Down
8 changes: 5 additions & 3 deletions src/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import { debounce } from './debounce';
export type SyncArgs = {
subscribe: (cb: () => unknown) => () => void;
syncFn: (signal: AbortSignal) => unknown;
wait: number;
options?: {
wait?: number;
notifyOnLeave?: boolean;
};
};

export function sync({ subscribe, syncFn, wait, options }: SyncArgs) {
export function sync({ subscribe, syncFn, options = {} }: SyncArgs) {
const { notifyOnLeave = false, wait = 0 } = options;

let isSyncing = false;
let abortController: AbortController | null = null;

Expand Down Expand Up @@ -41,7 +43,7 @@ export function sync({ subscribe, syncFn, wait, options }: SyncArgs) {
flushIfNeeded();
};

if (options?.notifyOnLeave) {
if (notifyOnLeave) {
window.addEventListener('beforeunload', onUnload);
}

Expand Down

0 comments on commit b936a37

Please sign in to comment.