diff --git a/README.md b/README.md index 9008460..a3dbc4d 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ await peer.joinRoom('host-peer-id'); // Rejects if connection fails or times out // Interact with the synced storage const currentState = peer.getStorage; -peer.updateStorageArray('players', 'add', { username: 'PeerEnjoyer4', level: 2 }); // Special method to enable simultaneous storage updates for arrays +peer.updateStorageArray('players', 'add-unique', { username: 'PeerEnjoyer4', level: 2 }); // Special method to enable simultaneous storage updates for arrays peer.updateStorage('latestPlayer', 'PeerEnjoyer4'); // Regular synced storage update // To leave the room, destroy the instance @@ -83,7 +83,7 @@ Creates a new PlayPeer instance with a specified peer ID and [PeerJS options](ht #### State Management - `updateStorage(key: string, value: any)`: Update a value in the synchronized storage -- `updateStorageArray(key: string, operation: 'add' | 'remove-matching' | 'update-matching', value: any, updateValue?: any)`: Safely update arrays in storage by adding, removing, or updating items. This is necessary for when array updates might be happening simultanously to ensure changes are being applied and not overwritten. +- `updateStorageArray(key: string, operation: 'add' | 'add-unique' | 'remove-matching' | 'update-matching', value: any, updateValue?: any)`: Safely update arrays in storage by adding, removing, or updating items. This is necessary for when array updates might be happening simultanously to ensure changes are being applied and not overwritten. Using add-unique instead of add ensures that this value can only be in the array once. - `onEvent(event: string, callback: Function)`: Register an event callback ##### Event types diff --git a/package.json b/package.json index 80d1e19..a84d155 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "playpeerjs", - "version": "1.1.7", + "version": "1.1.8", "description": "WebRTC-based wrapper for creating robust peer-2-peer multiplayer systems with ease.", "type": "module", "main": "dist/playpeer.js", diff --git a/src/index.js b/src/index.js index e595ff2..f1fc182 100644 --- a/src/index.js +++ b/src/index.js @@ -437,6 +437,20 @@ export default class PlayPeer { this.#storage[key].push(value); break; + case 'add-unique': + // Check if the value already exists (deep comparison for objects) + const uniqueIndex = updatedArray.findIndex(item => { + if (typeof value === 'object' && value !== null) { + return JSON.stringify(item) === JSON.stringify(value); + } + return item === value; // Strict equality for primitives + }); + + if (uniqueIndex == -1) { + this.#storage[key].push(value); // Add the unique value + } + break; + case 'remove-matching': // Remove matching value (deep comparison for objects) this.#storage[key] = updatedArray.filter(item => {