/*! © 2026 Yahoo, Inc. UDS v0.0.0-development */
import { Children, cloneElement, isValidElement } from "react";
import { isFunction } from "lodash-es";
//#region src/utils/intersperse.ts
/**
* Given an array of items, place an item between each of the original values with either a constant
* value or the result of a function which knows the index it is being inserted before.
*
* @example
* const ANIMALS = ["Lions", "Tigers", "Bears"];
* const animalesInterspersedWithAmpersands = intersperse(ANIMALS, "&");
* // ["Lions", "&", "Tigers", "&", "Bears"]
* console.log(animalesInterspersedWithAmpersands.join(" ") + '. OH MY!');
*/
const intersperse = (list, inter) => {
	const interFn = isFunction(inter) ? inter : () => inter;
	return list.flatMap((item, i) => i !== 0 ? [interFn(i), item] : [item]);
};
/**
* Given ReactNode, if it is a list of children nodes, place a new React node between each of the
* original nodes with either a constant ReactElement or the result of a function which knows the
* index it is being inserted before.
*
* @example
* const SplitParagraphsWithHorizontalRule = ({ paragraphs }: { paragraphs: string[] }) => {
*   const paragraphNodes =  paragraphs.map((str) => <p>{str}</p>);
*
*   return (<div>
*     {intersperseReactChildren(paragraphNodes, <hr />)}
*   </div>);
* }
*/
const intersperseReactChildren = (children, inter) => {
	return intersperse(Children.toArray(children), (i) => {
		const node = isFunction(inter) ? inter(i) : inter;
		return isValidElement(node) ? cloneElement(node, {
			...node.props,
			key: node.key ?? `interspersed-${i}`
		}) : null;
	});
};
//#endregion
export { intersperse, intersperseReactChildren };
