Accept random seed from UI for random sorting (#328)

This commit is contained in:
Infinite 2020-02-02 23:09:57 +01:00
parent 79f69b4d61
commit 3bbcc65521

View file

@ -69,6 +69,7 @@ export class ListFilterModel {
public displayModeOptions: DisplayMode[] = [];
public criterionOptions: ICriterionOption[] = [];
public criteria: Array<Criterion<any, any>> = [];
public randomSeed = -1;
private static createCriterionOption(criterion: CriterionType) {
return new CriterionOption(Criterion.getLabel(criterion), criterion);
@ -193,6 +194,19 @@ export class ListFilterModel {
const params = rawParms as IQueryParameters;
if (params.sortby !== undefined) {
this.sortBy = params.sortby;
// parse the random seed if provided
const randomPrefix = "random_";
if (this.sortBy && this.sortBy.startsWith(randomPrefix)) {
const seedStr = this.sortBy.substring(randomPrefix.length);
this.sortBy = "random";
try {
this.randomSeed = Number.parseInt(seedStr, 10);
} catch (err) {
// ignore
}
}
}
if (params.sortdir === "asc" || params.sortdir === "desc") {
this.sortDirection = params.sortdir;
@ -227,6 +241,28 @@ export class ListFilterModel {
}
}
private setRandomSeed() {
if (this.sortBy === "random") {
// #321 - set the random seed if it is not set
if (this.randomSeed === -1) {
// generate 8-digit seed
this.randomSeed = Math.floor(Math.random() * (10 ** 8));
}
} else {
this.randomSeed = -1;
}
}
private getSortBy(): string | undefined {
this.setRandomSeed();
if (this.sortBy === "random") {
return `${this.sortBy}_${this.randomSeed.toString()}`;
}
return this.sortBy;
}
public makeQueryParameters(): string {
const encodedCriteria: string[] = [];
this.criteria.forEach(criterion => {
@ -239,7 +275,7 @@ export class ListFilterModel {
});
const result = {
sortby: this.sortBy,
sortby: this.getSortBy(),
sortdir: this.sortDirection,
disp: this.displayMode,
q: this.searchTerm,
@ -256,7 +292,7 @@ export class ListFilterModel {
q: this.searchTerm,
page: this.currentPage,
per_page: this.itemsPerPage,
sort: this.sortBy,
sort: this.getSortBy(),
direction:
this.sortDirection === "asc"
? SortDirectionEnum.Asc