/**
 * arrayTreeFilter.js
 *
 * @Author: zhangce
 * @Date: 17/8/31 上午11:09
 */

var arrayTreeFilter = function arrayTreeFilter(data, filterFn) {
    var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};

    options.childrenKeyName = options.childrenKeyName || 'children';
    var children = data || [];
    var result = [];
    var level = 0;
    var filterCallBack = function filterCallBack(item) {
        return filterFn(item, level);
    };
    do {
        var foundItem = children.filter(filterCallBack)[0];
        if (!foundItem) {
            break;
        }
        result.push(foundItem);
        children = foundItem[options.childrenKeyName] || [];
        level += 1;
    } while (children.length);

    return result;
};

var treeToPath = function treeToPath(tree) {
    var path = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];
    var currentPath = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];

    tree.forEach(function (item, index) {
        if (index !== 0) {
            currentPath.pop();
        }
        currentPath.push(item);

        if (item.children && item.children.length) {
            treeToPath(item.children, path, currentPath);
        } else {
            path.push(currentPath.slice(0));
        }
    });

    currentPath.pop();

    return path;
};

export { arrayTreeFilter, treeToPath };