Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created April 6, 2015 04:57
Show Gist options
  • Save aleclarson/90acdc6594ad6e1da47e to your computer and use it in GitHub Desktop.
Save aleclarson/90acdc6594ad6e1da47e to your computer and use it in GitHub Desktop.
getCommonDirectory of two paths
Path = require "path"
getDirectories = (path) ->
dirs = []
path = Path.resolve path unless Path.isAbsolute path
dirs.push Path.basename path if Path.extname(path) is ""
loop
dir = Path.dirname path
break if dir is "/"
dirs.push dir.slice dir.lastIndexOf("/") + 1
path = dir
return dirs
getCommonDirectory = (a, b) ->
result = []
b = Path.resolve b unless Path.isAbsolute b
dirs = { a: getDirectories(a), b: getDirectories(b) }
loop
dir = { a: dirs.a.pop(), b: dirs.b.pop() }
break unless dir.a? and dir.b?
result.push dir.a if dir.a is dir.b
return if result.length > 0 then result.join "/" else null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment