diff --git a/src/util/_impl/_sorted_impl.scad b/src/util/_impl/_sorted_impl.scad new file mode 100644 index 00000000..b59854d0 --- /dev/null +++ b/src/util/_impl/_sorted_impl.scad @@ -0,0 +1,14 @@ +function _sorted(lt, less, gt_eq) = + let(leng = len(lt)) + leng <= 1 ? lt : + leng == 2 ? gt_eq(lt[1], lt[0]) ? lt : [lt[1], lt[0]] : + let( + pivot = lt[0], + before = [for(j = 1; j < leng; j = j + 1) if(less(lt[j], pivot)) lt[j]], + after = [for(j = 1; j < leng; j = j + 1) if(gt_eq(lt[j], pivot)) lt[j]] + ) + [each _sorted(before, less, gt_eq), pivot, each _sorted(after, less, gt_eq)]; + +function _sorted_default(lt) = _sorted(lt, function(a, b) a < b, function(a, b) a >= b); + +function _sorted_cmp(lt, cmp) = _sorted(lt, function(a, b) cmp(a, b) < 0, function(a, b) cmp(a, b) >= 0); \ No newline at end of file diff --git a/src/util/sorted.scad b/src/util/sorted.scad new file mode 100644 index 00000000..f79d7085 --- /dev/null +++ b/src/util/sorted.scad @@ -0,0 +1,14 @@ +/** +* sort.scad +* +* @copyright Justin Lin, 2022 +* @license https://opensource.org/licenses/lgpl-3.0.html +* +* @see https://openhome.cc/eGossip/OpenSCAD/lib3x-sorted.html +* +**/ + +use <_impl/_sorted_impl.scad>; + +function sorted(lt, cmp = undef) = + is_undef(cmp) ? _sorted_default(lt) : _sorted_cmp(lt, cmp); \ No newline at end of file diff --git a/test/test_all.scad b/test/test_all.scad index 23e71315..7e02d1c0 100644 --- a/test/test_all.scad +++ b/test/test_all.scad @@ -65,7 +65,7 @@ include ; include ; include ; include ; -include ; +include ; include ; include ; include ; @@ -80,7 +80,7 @@ include ; include ; include ; include ; - +include ; // Voxel include ; diff --git a/test/util/test_sorted.scad b/test/util/test_sorted.scad new file mode 100644 index 00000000..5d2c5395 --- /dev/null +++ b/test/util/test_sorted.scad @@ -0,0 +1,25 @@ +use ; + +module test_sorted() { + echo("==== test_sorted ===="); + + assert([1, 2, 3, 4, 5, 6] == sorted([1, 6, 2, 5, 4, 3]) +); + + assert( + [[2, 0, 0], [5, 0, 0], [7, 0, 0], [9, 0, 0], [10, 0, 0]] == + sorted([[2, 0, 0], [5, 0, 0], [7, 0, 0], [9, 0, 0], [10, 0, 0]]) + ); + + assert( + [[2, 0, 0], [5, 0, 0], [7, 0, 0], [9, 0, 0], [10, 0, 0]] == + sorted([[10, 0, 0], [5, 0, 0], [7, 0, 0], [2, 0, 0], [9, 0, 0]], cmp = function(a, b) a[0] - b[0]) + ); + + ascending = function(e1, e2) e1 - e2; + descending = function(e1, e2) e2 - e1; + assert(sorted([2, 1, 3, 5, 4], ascending) == [1, 2, 3, 4, 5]); + assert(sorted([2, 1, 3, 5, 4], descending) == [5, 4, 3, 2, 1]); +} + +test_sorted();