Skip to content

Instantly share code, notes, and snippets.

@ganeshrvel
Created August 24, 2020 08:17
Show Gist options
  • Save ganeshrvel/62f15d46e0c3756ea0e3b0b9d6cecc8b to your computer and use it in GitHub Desktop.
Save ganeshrvel/62f15d46e0c3756ea0e3b0b9d6cecc8b to your computer and use it in GitHub Desktop.
Sorting file path list - algorithm (javascript)
const pathList = ['/path1/abc', '/path1/123', '/path2/xyz', '/path2/0123', '/path3/123', '/path3/xyz','/path1/'];
const splittedArr = pathList.map(a => a.split('/'));
function sortPath(arr, index, start, end) {
arr.sort((a, b) => {
if (a < b) return -1;
if (a > b) return 1;
return 0;
});
const _buckets = [];
let _currentString;
let _lastInsertedBucketIndex = -1;
for (let i = start; i < end; i += 1) {
const item = arr[i][index];
if (item !== _currentString) {
_currentString = item;
if (_buckets[_lastInsertedBucketIndex] !== undefined) {
_buckets[_lastInsertedBucketIndex].push(i - 1);
}
_lastInsertedBucketIndex += 1;
_buckets.push([i]);
}
if (i === end - 1 && _buckets[_lastInsertedBucketIndex] !== undefined) {
if (_buckets[_lastInsertedBucketIndex][1] === undefined) {
_buckets[_lastInsertedBucketIndex].push(i);
}
}
}
if (_buckets.length > 0) {
for (let i = 0; i < _buckets.length; i += 1) {
sortPath(arr, index + 1, _buckets[i][0], _buckets[i][1] + 1);
}
}
return arr;
}
sortedArr = sortPath(splittedArr, 0, 0, splittedArr.length);
const joinedPathArr = sortedArr.map(a => a.join('/'));
console.log(joinedPathArr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment