Fnykis
7/4/2017 - 3:34 AM

Find a layer from name and type

Find a layer from name and type

/*
  FUNCTION DESCRIPTION:
    Will find a layer by looking for name and type
    
  INPUT:
    nameInput (String) = The name of the layer you're looking for
    OR
    nameInput (Array) = Multiple names to add to the results (can be used as alternative spelling)
    type (String) = "ArtLayer" or "LayerSet" or "Any"
    
  OUTPUT:
    Returns the matching layer as an object
    If multiple layers were found - returns an array of those layers
    Returns Null if no layer was found
    
  NOTE:
    None
*/

function findLayer(nameInput, type) {
	
	function diveDeeper(layerInput) {
		
        if (typeof nameInput == "string") {
            if (type == "Any") {
                if (layerInput.name == nameInput) results.push(layerInput);
            }  else {
                if (layerInput.name == nameInput && layerInput.typename == type) results.push(layerInput);
            }
        } else {
            while (layerInput.name != nameInput[variantIndex]) {
                variantIndex++;
                if (variantIndex >= nameInput.length) break;
            }

            if (type == "Any") {
                if (layerInput.name == nameInput[variantIndex]) results.push(layerInput);
            }  else {
                if (layerInput.name == nameInput[variantIndex] && layerInput.typename == type) results.push(layerInput);
            }

            variantIndex = 0;
        }
		
		if (layerInput.typename === "LayerSet") {
			if (layerInput.layers.length > 0) {
				for (var indexDive = layerInput.layers.length - 1; indexDive > -1; indexDive--) diveDeeper(layerInput.layers[indexDive]);
			}
		}
		
	}
	
    var variantIndex = 0;
	var results = [];

    for (var indexAll = 0; indexAll < activeDocument.layers.length; indexAll++) diveDeeper(activeDocument.layers[indexAll]);
	
	if (!results.length) return null;
	if (results.length == 1) return results[0];
	if (results.length > 1) return results;
	
}