import { is } from '@ma-shop/is'
/**
* @name renderIf
* @author Tyler Benton
* @description This function is used to help with condition rendering.
* It is a very flexible function so there's many ways you can utilize it.
* @arg {*} ...predicates - The conditions on if the element should be displayed or not.
* note that you can pass in anything not just a boolean. It will get passed into `is.empty`
* so instead of passing in `array.length` just pass in `array`.
* @arg {Component, function} - The last argument is always the component or the function
* @example passed in an element
* render() {
* return renderIf(this.props.if, children, (
* ...
* ))
* }
* @example as a callback
* render() {
* return renderIf(this.props.if, something === 'woohoo', () => (
* ...
* ))
* }
*/
export function renderIf (...predicates: any) {
const render = predicates.pop()
// this is the most performant way of handling multiple predicates
// https://jsperf.com/if-vs-for-loop
for (const predicate of predicates) {
if (is.empty(predicate)) return null
}
if (!is.function(render)) {
throw new Error('must pass a render function last to avoid unnecessary rerenders')
}
return render()
}