const { isValidElement } = require("react");
const { isArray } = Array;
const ArrayMap = Array.prototype.map;
const { hasOwnProperty } = Object;
const toArray = value => value === void(0) ? [] : [].concat(value);
module.exports = primitives => function collapse(element)
{
if (isArray(element))
return ArrayMap.call(element, collapse).filter(x => !!x);
if (element === false || typeof element === "undefined")
return false;
// For strings, etc.?...
if (!isValidElement(element))
return element;
const { type, props } = element;
const kind = typeof type;
return kind === "function" ? collapse(type(props)) :
kind === "string" ?
hasOwnProperty.call(primitives, type) ?
collapse(primitives[type](props)) :
{ ...element, props:
{ ...props,
children: collapse(toArray(props.children)) } } :
(() => { throw Errors.InvalidReactType(kind) })();
}
const Errors =
{
InvalidElement: type => new Error(
`Custom React rendering could not render non-React object of type ` +
`"${type}".`),
InvalidReactType: type => new Error(
`Custom React rendering could not render element with type "${type}"`),
NoDefinitionForPrimitiveElement: type => new Error(
`Custom React rendering had no definitions for primitive element ` +
`<${type}>.`)
}