import _ from 'lodash';

/**
 * Uses a finder function to locate an object in an array, and then merges another object into that object, returning
 * a new copy of the array with the merged object
 *
 * @param {Array} array the array to search within
 * @param {Function} finder the function to use to find the target object in the array
 * @param {Object} objectToMerge the object to merge into the target object
 * @returns {Array} copy of the source array with new target object with new object merged in
 */
export default function mergeObjectInArray(array, finder, objectToMerge) {
    const index = _.findIndex(array, finder);
    if (index === -1) {
        return array;
    }

    return [
        ...array.slice(0, index),
        _.assign({}, array[index], objectToMerge),
        ...array.slice(index + 1),
    ];
}
