Home Reference Source

src/groups/Group.ts

import {difference, union} from 'lodash-es';

interface GroupData {
	id: string;
	name: string;
	owner: string;
	participants: Iterable<string>;
}

/**
 * This class allows access to the details of each group
 * @link {GroupManager#.getGroups()} method should be used to obtain the list
 * of instances of this class.
 */
export class Group {
	/** The unique id that identifies the group */
	readonly id: string;

	/** The name of the group */
	readonly name: string;

	/** The user that owns the group */
	readonly owner: string;

	/**
	 * A list of the users that belong to the group
	 */
	readonly participants: readonly string[];

	/** @ignore */
	static of({id, name, owner, participants}: GroupData): Group {
		return new Group(id, name, owner, participants);
	}

	private constructor(id: string, name: string, owner: string, participants: Iterable<string>) {
		this.id = id;
		this.name = name;
		this.owner = owner;
		this.participants = [...participants];
	}

	/**
	 * Creates a new Group object with the provided parameter changed
	 */
	with({name = this.name, participants = this.participants} = {}): Group {
		return new Group(this.id, name, this.owner, participants);
	}

	/**
	 * Creates a new Group object adding the provided participants
	 */
	plusParticipants(...participants: string[]): Group {
		return this.with({participants: union(this.participants, participants)});
	}

	/**
	 * Creates a new Group object removing the provided participants
	 */
	minusParticipants(...participants: string[]): Group {
		return this.with({participants: difference(this.participants, participants)});
	}
}