1 | 'use strict'
|
2 |
|
3 | const size = require('../../utils/array').size
|
4 |
|
5 | function factory (type, config, load, typed) {
|
6 | const matrix = load(require('../../type/matrix/function/matrix'))
|
7 | const compareAsc = load(require('../relational/compare'))
|
8 | const compareDesc = function (a, b) {
|
9 | return -compareAsc(a, b)
|
10 | }
|
11 | const compareNatural = load(require('../relational/compareNatural'))
|
12 |
|
13 | |
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 |
|
42 |
|
43 |
|
44 | const sort = typed('sort', {
|
45 | 'Array': function (x) {
|
46 | _arrayIsVector(x)
|
47 | return x.sort(compareAsc)
|
48 | },
|
49 |
|
50 | 'Matrix': function (x) {
|
51 | _matrixIsVector(x)
|
52 | return matrix(x.toArray().sort(compareAsc), x.storage())
|
53 | },
|
54 |
|
55 | 'Array, function': function (x, _comparator) {
|
56 | _arrayIsVector(x)
|
57 | return x.sort(_comparator)
|
58 | },
|
59 |
|
60 | 'Matrix, function': function (x, _comparator) {
|
61 | _matrixIsVector(x)
|
62 | return matrix(x.toArray().sort(_comparator), x.storage())
|
63 | },
|
64 |
|
65 | 'Array, string': function (x, order) {
|
66 | _arrayIsVector(x)
|
67 | return x.sort(_comparator(order))
|
68 | },
|
69 |
|
70 | 'Matrix, string': function (x, order) {
|
71 | _matrixIsVector(x)
|
72 | return matrix(x.toArray().sort(_comparator(order)), x.storage())
|
73 | }
|
74 | })
|
75 |
|
76 | sort.toTex = undefined
|
77 |
|
78 | |
79 |
|
80 |
|
81 |
|
82 |
|
83 | function _comparator (order) {
|
84 | if (order === 'asc') {
|
85 | return compareAsc
|
86 | } else if (order === 'desc') {
|
87 | return compareDesc
|
88 | } else if (order === 'natural') {
|
89 | return compareNatural
|
90 | } else {
|
91 | throw new Error('String "asc", "desc", or "natural" expected')
|
92 | }
|
93 | }
|
94 |
|
95 | |
96 |
|
97 |
|
98 |
|
99 |
|
100 |
|
101 | function _arrayIsVector (array) {
|
102 | if (size(array).length !== 1) {
|
103 | throw new Error('One dimensional array expected')
|
104 | }
|
105 | }
|
106 |
|
107 | |
108 |
|
109 |
|
110 |
|
111 |
|
112 |
|
113 | function _matrixIsVector (matrix) {
|
114 | if (matrix.size().length !== 1) {
|
115 | throw new Error('One dimensional matrix expected')
|
116 | }
|
117 | }
|
118 |
|
119 | return sort
|
120 | }
|
121 |
|
122 | exports.name = 'sort'
|
123 | exports.factory = factory
|