-
Notifications
You must be signed in to change notification settings - Fork 0
/
reorder-columns.component.ts
66 lines (59 loc) · 1.87 KB
/
reorder-columns.component.ts
1
2
3
4
5
6
7
8
9
10
11
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'reorder-order',
templateUrl: 'reorder-columns.component.html',
styleUrls: ['./reorder-columns.component.scss'],
})
export class ColumnReorderDialog {
currentColumnIndex = null;
newPositionColumnIndex = null;
constructor(
public dialogRef: MatDialogRef<ColumnReorderDialog>,
@Inject(MAT_DIALOG_DATA) public data: string[]
) {}
change(index) {
if (this.currentColumnIndex === null) {
this.currentColumnIndex = index;
} else {
this.newPositionColumnIndex = index;
this.data = this.immutableReorder(
this.data,
this.currentColumnIndex,
this.newPositionColumnIndex
);
this.currentColumnIndex = null;
this.newPositionColumnIndex = null;
}
}
immutableReorder(array: string[], fromIndex: number, toIndex: number) {
return array.reduce((prev, current, index, wholeArray) => {
// if index of starting is the same as end, we want just to add current index of iteration to new array
if (fromIndex === toIndex) {
prev = [...prev, current];
}
// in case that index of iteration is equal to our starting point we want to skip
if (index === fromIndex) {
return prev;
}
if (fromIndex < toIndex) {
prev = [...prev, current];
}
// if index of iteration is equal to toIndex, we add to our new array item[fromIndex] because this creates the new position
if (index === toIndex) {
prev = [...prev, wholeArray[fromIndex]];
}
if (fromIndex > toIndex) {
prev = [...prev, current];
}
return prev;
}, []);
// initial value empty array
}
close() {
this.dialogRef.close(null);
}
save() {
this.dialogRef.close([...this.data]);
}
}