1 |
|
2 |
|
3 |
|
4 | 'use strict';
|
5 |
|
6 | const Base = require('./DataProvider');
|
7 |
|
8 | module.exports = class ArrayDataProvider extends Base {
|
9 |
|
10 | prepareTotalCount () {
|
11 | return this.allModels ? this.allModels.length : 0;
|
12 | }
|
13 |
|
14 | prepareModels () {
|
15 | let models = this.allModels || [];
|
16 | if (this.sort) {
|
17 | models = this.sortModels(models, this.sort);
|
18 | }
|
19 | if (this.pagination) {
|
20 | this.pagination.totalCount = this.totalCount;
|
21 | if (this.pagination.pageSize > 0) {
|
22 | const offset = this.pagination.getOffset();
|
23 | models = models.slice(offset, offset + this.pagination.getLimit());
|
24 | }
|
25 | }
|
26 | return models;
|
27 | }
|
28 |
|
29 | sortModels (models, sort) {
|
30 | const Sort = require('./Sort');
|
31 | const orders = sort.getOrders();
|
32 | if (orders) {
|
33 | const directions = {};
|
34 | for (const attr of Object.keys(orders)) {
|
35 | directions[attr] = orders[attr] === Sort.ASC ? 1 : -1;
|
36 | }
|
37 | models.sort(this.compareModels.bind(this, orders, directions));
|
38 | }
|
39 | return models;
|
40 | }
|
41 |
|
42 | compareModels (orders, directions, a, b) {
|
43 | for (const attr of Object.keys(orders)) {
|
44 | const result = a[attr].toString().localeCompare(b[attr].toString());
|
45 | if (result !== 0) {
|
46 | return result * directions[attr];
|
47 | }
|
48 | }
|
49 | return 0;
|
50 | }
|
51 | }; |
\ | No newline at end of file |