/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

'use strict';

/**
 * Returns a new array with unique elements based on a specified property.
 * When duplicates are found, the last occurrence is preferred.
 *
 * @param array - The array to process
 * @param key - The property name to check for uniqueness or a function that extracts the value
 * @returns A new array with unique elements
 */
module.exports = function uniqByLast( key, array ) {
	const seen = new Map();

	// Process from right to left to keep last occurrences
	return array
		.slice()
		.reverse()
		.filter( item => {
			const value = typeof key === 'function' ? key( item ) : item[ key ];
			if ( seen.has( value ) ) {
				return false;
			}
			seen.set( value, true );
			return true;
		} )
		.reverse();
};
