Skip to content

Instantly share code, notes, and snippets.

@isaacw
Last active February 12, 2017 00:46
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaacw/86f820aae18b8fb5d350f334caf6a2a4 to your computer and use it in GitHub Desktop.
Save isaacw/86f820aae18b8fb5d350f334caf6a2a4 to your computer and use it in GitHub Desktop.
Creates convenience refs on imported layers so that we don't have to use Layer::childrenWithName; can be applied to all descendant layers while maintaining hierarchy.
# Layer::createChildrenRefs
# Creates convenience refs on imported layers so that we don't have to use Layer::childrenWithName.
# Pass recursive=true to do this for all descendant layers while maintaining hierarchy.
Layer::createChildrenRefs = (recursive=false) ->
# Regex pattern for finding trailing numbers
rgx = /(\d+$)/g
for layer in @.children
# Create base name by stripping out trailing numbers
base = layer.name.replace rgx, ""
# Do any of the layer's siblings have the same base?
hasMatchingBase = layer.siblings.some (sibling) ->
base is sibling.name.replace rgx, ""
# Determine which name to use for the key, ensure sibling names are unique
# Don't rename layer if doing so will result in duplicate sibling names
key = if hasMatchingBase then layer.name else base
# Set reference
@[key] = layer
# Should we also do this for current layer's children?
if recursive and layer.children.length > 0
layer.createChildrenRefs(recursive)
@TheDahv
Copy link

TheDahv commented Sep 26, 2016

Lovely. Do you need to create a new instance of rgx for every run of the loop, or would you save on allocations if you create it once and share it among all executions?

@isaacw
Copy link
Author

isaacw commented Sep 26, 2016

@TheDahv Ahh yes! Great point, just revised it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment