Skip to content

Instantly share code, notes, and snippets.

@bradparker
Last active May 11, 2016 13:00
Show Gist options
  • Save bradparker/602634c1aabc52c59f5a7a9f117ea9d6 to your computer and use it in GitHub Desktop.
Save bradparker/602634c1aabc52c59f5a7a9f117ea9d6 to your computer and use it in GitHub Desktop.
Exclude parent dirs
const assert = require('assert')
const isEqual = (a, b) => {
if (a.length !== b.length) return false
return a.every((aElem, index) => aElem === b[index])
}
// flip :: (a -> b -> c) -> (b -> a -> c)
const flip = (f) => (a, b) => f(b, a)
const isParent = (a, b) => {
const aParts = a.split('/')
const bParts = b.split('/')
return isEqual(aParts, bParts.slice(0, aParts.length))
}
const isChild = flip(isParent)
assert(isParent('a/b', 'a/b/c'))
assert(!isParent('a/b', 'a/c/c'))
assert(isChild('a/b/c', 'a/b'))
assert(!isChild('a/b/c', 'a/c'))
const isParentOfAny = (dir, dirs) => (
dirs.some((a) => (
isParent(dir, a)
))
)
const withoutParentsOf = (dir, dirs) => (
dirs.filter((a) => !isParent(a, dir))
)
const excludeParents = (dirs) => (
dirs.reduce((acc, dir) => (
(!isParentOfAny(dir, acc))
? withoutParentsOf(dir, acc).concat(dir)
: acc
), [])
)
const resOne = excludeParents([
'foo/bar/baz',
'foo/bar',
'foo/bar/baz/quix',
'foo'
])
assert(
(resOne[0] === 'foo/bar/baz/quix') &&
(resOne.length === 1)
)
console.log('Test 1 a ok!')
const resTwo = excludeParents([
'foo/bar/baz',
'foo/bar',
'foo',
'bar',
'bar/baz'
])
assert(
(resTwo[0] === 'foo/bar/baz') &&
(resTwo[1] === 'bar/baz') &&
(resTwo.length === 2)
)
console.log('Test 2 a ok!')
const excludeParentsAlt = (dirs) => (
dirs.sort().reduce((acc, dir) => {
if (acc.length === 0) return [dir]
if (isChild(dir, acc[acc.length - 1])) {
return acc.slice(0, acc.length - 1).concat(dir)
} else {
return acc.concat(dir)
}
}, [])
)
const resThree = excludeParentsAlt([
'foo/bar/baz',
'foo/bar',
'foo/bar/baz/quix',
'foo'
])
assert(
(resThree[0] === 'foo/bar/baz/quix') &&
(resThree.length === 1)
)
console.log('Test 3 a ok!')
const resFour = excludeParentsAlt([
'foo/bar/baz',
'foo/bar',
'foo',
'bar',
'bar/baz'
])
assert(
(resFour[0] === 'bar/baz') &&
(resFour[1] === 'foo/bar/baz') &&
(resFour.length === 2)
)
console.log('Test 4 a ok!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment