Module: DaruLite::Vector::Sortable
- Included in:
- DaruLite::Vector
- Defined in:
- lib/daru_lite/vector/sortable.rb
Constant Summary collapse
- DEFAULT_SORTER =
lambda { |(lv, li), (rv, ri)| if lv.nil? && rv.nil? li <=> ri elsif lv.nil? -1 elsif rv.nil? 1 else lv <=> rv end }
Instance Method Summary collapse
-
#reorder(order) ⇒ Object
Non-destructive version of #reorder!.
-
#reorder!(order) ⇒ Object
Reorder the vector with given positions.
-
#sort(opts = {}, &block) ⇒ Object
Sorts a vector according to its values.
-
#sort_by_index(opts = {}) ⇒ Vector
Sorts the vector according to it’s`Index` values.
-
#sorted_data(&block) ⇒ Object
Just sort the data and get an Array in return using Enumerable#sort.
Instance Method Details
#reorder(order) ⇒ Object
Non-destructive version of #reorder!
97 98 99 |
# File 'lib/daru_lite/vector/sortable.rb', line 97 def reorder(order) dup.reorder! order end |
#reorder!(order) ⇒ Object
Unlike #reindex! which takes index as input, it takes positions as an input to reorder the vector
Reorder the vector with given positions
88 89 90 91 92 93 94 |
# File 'lib/daru_lite/vector/sortable.rb', line 88 def reorder!(order) @index = @index.reorder order data_array = order.map { |i| @data[i] } @data = cast_vector_to @dtype, data_array, @nm_dtype update_position_cache self end |
#sort(opts = {}, &block) ⇒ Object
Sorts a vector according to its values. If a block is specified, the contents will be evaluated and data will be swapped whenever the block evaluates to true. Defaults to ascending order sorting. Any missing values will be put at the end of the vector. Preserves indexing. Default sort algorithm is quick sort.
Options
-
:ascending- if false, will sort in descending order. Defaults to true. -
:type- Specify the sorting algorithm. Only supports quick_sort for now.
Usage
v = DaruLite::Vector.new ["My first guitar", "jazz", "guitar"]
# Say you want to sort these strings by length.
v.sort(ascending: false) { |a,b| a.length <=> b.length }
20 21 22 23 24 25 26 27 28 29 |
# File 'lib/daru_lite/vector/sortable.rb', line 20 def sort(opts = {}, &block) opts = { ascending: true }.merge(opts) vector_index = resort_index(@data.each_with_index, opts, &block) vector, index = vector_index.transpose index = @index.reorder index DaruLite::Vector.new(vector, index: index, name: @name, dtype: @dtype) end |
#sort_by_index(opts = {}) ⇒ Vector
Sorts the vector according to it’s`Index` values. Defaults to ascending order sorting.
49 50 51 52 53 54 |
# File 'lib/daru_lite/vector/sortable.rb', line 49 def sort_by_index(opts = {}) opts = { ascending: true }.merge(opts) _, new_order = resort_index(@index.each_with_index, opts).transpose reorder new_order end |
#sorted_data(&block) ⇒ Object
Just sort the data and get an Array in return using Enumerable#sort. Non-destructive. :nocov:
71 72 73 |
# File 'lib/daru_lite/vector/sortable.rb', line 71 def sorted_data(&block) @data.to_a.sort(&block) end |