Skip to content

Instantly share code, notes, and snippets.

@rsms
Created January 18, 2017 21:30
Show Gist options
  • Select an option

  • Save rsms/5f6c61515cc23e37209f20f360b95c85 to your computer and use it in GitHub Desktop.

Select an option

Save rsms/5f6c61515cc23e37209f20f360b95c85 to your computer and use it in GitHub Desktop.
function commonPrefixLen(names, sep) {
const sc = sep.charCodeAt(0);
for (let pos = 0; ; pos++) {
for (let i = 0; i < names.length; i++) {
let c = names[i].charCodeAt(pos)
if (c && c == names[0].charCodeAt(pos)) {
continue;
}
while (pos > 0 && names[0].charCodeAt(--pos) != sc) {}
return pos;
}
}
return 0;
}
let inpaths = [
'/foo/bar/cat/bar/bobso',
'/foo/bar/cat/bar/b',
'/foo/bar/cat/ken/lolcat',
'/foo/bar/cat/a',
'/foo/bar/cat',
]
console.log(inpaths[0].substr(0, commonPrefixLen(inpaths, '/')))
// output: "/foo/bar"
inpaths = [
'/foo/bar/cat/bar/bobso',
'/foo/bar/cat/bar/b',
'/foo/bar/cat/ken/lolcat',
'/foo/bar/cat/a',
'/bar',
]
console.log(inpaths[0].substr(0, commonPrefixLen(inpaths, '/')))
// output: ""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment