//AE合成度遍历示例 v1.0 2022-05-04
//Raymond Yan 2022 (RaymondClr@outlook.com / QQ: 1107677019)

function _arrayEach(array, iteratee) {
    var index = -1;
    var length = array.length;
    while (++index < length) iteratee(array[index], index, array);
}

function _contains(array, value) {
    var index = -1;
    var length = array.length;
    while (++index < length) if (array[index] === value) return true;
    return false;
}

function _stubTrue() {
    return true;
}

function isCompLayer(layer) {
    return layer.source instanceof CompItem;
}

function baseEachLayers(compItem, iteratee) {
    var index = 0;
    var numLayers = compItem.numLayers + 1;
    while (++index < numLayers) iteratee(compItem.layer(index), index);
}

function baseFindLayer(compItem, predicate, iteratee) {
    var compLayers = [];
    baseEachLayers(compItem, function (layer) {
        iteratee(layer);
        if (isCompLayer(layer) && predicate(layer)) compLayers.push(layer);
    });
    _arrayEach(compLayers, function (layer) {
        baseFindLayer(layer.source, predicate, iteratee);
    });
}

function eachLayersDeep(compItem, iteratee) {
    baseFindLayer(compItem, _stubTrue, iteratee);
}

function eachLayersDeepOnce(compItem, iteratee) {
    var seen = [];
    baseFindLayer(
        compItem,
        function (layer) {
            var id = layer.source.id;
            return _contains(seen, id) ? false : (seen.push(id), true);
        },
        iteratee
    );
}

//用法一:无论子合成是否存在重复,都进行遍历。

var result = [];

eachLayersDeep(app.project.activeItem.selectedLayers[0].source, function (layer) {
    result.push(layer.name);
});

$.writeln(result.join("\n"));

//用法二:当子合成存在重复时,只遍第一次发现的子合成。

var result = [];

eachLayersDeepOnce(app.project.activeItem.selectedLayers[0].source, function (layer) {
    result.push(layer.name);
});

$.writeln(result.join("\n"));