import { typeNumber } from "./util";
function toArray(original) {
    var children = [],
        lastText,
        hasText,
        child,
        temp = Array.isArray(original) ? original.slice(0) : [original]

    while (temp.length) {
        //比较巧妙地判定是否为子数组
        if ((child = temp.pop()) && child.pop) {
            if (child.toJS) {
                //兼容Immutable.js
                child = child.toJS();
            }
            for (let i = 0; i < child.length; i++) {
                temp[temp.length] = child[i];
            }
        } else {
            // eslint-disable-next-line
            var childType = typeNumber(child);

            if (childType < 3 // 0, 1, 2
            ) {
                continue;
            }

            if (childType < 6) {
                //!== 'object' 不是对象就是字符串或数字
                if (hasText) {
                    children[0] = child + lastText;
                    continue;
                }
                child = child + ""
                lastText = child;
                hasText = true
            } else {
                hasText = false
                lastText = null;
            }

            children.unshift(child);
        }
    }
    return children
}
export const Children = {
    only(children) {
        //only方法接受的参数只能是一个对象，不能是多个对象（数组）。
        if (Array.isArray(children)) {
            children = children[0]
        }
        if (children && children.vtype)
            return children
        throw new Error('expect only one child')
    },
    count(children) {
        console.warn('请限制使用Children.count')
        return toArray(children).length
    },
    forEach(children, callback, context) {
        console.warn('请限制使用Children.forEach')
        toArray(children).forEach(callback, context);
    },
    map(children, callback, context) {
        console.warn('请限制使用Children.map')
        return toArray(children).map(callback, context);
    },
    toArray: toArray
};

