Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix View sort does not support non-numerical prop #197

Merged
merged 1 commit into from
Jul 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/datx/src/View.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export class View<T extends PureModel = PureModel> extends ToMany<T> {
? (item): any => item[this.sortMethod as 'string']
: this.sortMethod;

list.sort((a: T, b: T) => sortFn(a) - sortFn(b));
list.sort((a: T, b: T) => (sortFn(a) === sortFn(b) ? 0 : sortFn(a) > sortFn(b) ? 1 : -1));
}

const instances = observable.array(list, { deep: false });
Expand Down
33 changes: 33 additions & 0 deletions packages/datx/test/view.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,39 @@ describe('View', () => {
expect(item2b && item2b.key).toBe(2);
});

it('should be able to sort models by non-numerical prop', () => {
class Foo extends Model {
public static type = 'foo';

@Attribute()
public key!: string;
}
class AppCollection extends Collection {
public static types = [Foo];
}

const collection = new AppCollection();
const foos = collection.add([{ key: 'abd' }, { key: 'bbf' }, { key: 'ecf' }], Foo);
const viewInstance = new View(Foo, collection, (item: Foo) => item.key, foos);

expect(viewInstance).toHaveLength(3);
const item0a = viewInstance.list[0];
const item2a = viewInstance.list[2];

expect(item0a && item0a.key).toBe('abd');
expect(item2a && item2a.key).toBe('ecf');

const foo0 = collection.add({ key: 'ccc' }, Foo);

expect(viewInstance).toHaveLength(3);
viewInstance.add(foo0);
const item0b = viewInstance.list[0];
const item2b = viewInstance.list[2];

expect(item0b && item0b.key).toBe('abd');
expect(item2b && item2b.key).toBe('ccc');
});

it('should be able to update sort method', () => {
class Foo extends Model {
public static type = 'foo';
Expand Down