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

Random ordered function #381

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/lib-js-core/src/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,9 @@ export class DataClass<ClassSchema = {
results.filter(({id}) =>
uniqueIds.includes(id) ? false : uniqueIds.push(id)
)
if (this.query.random_order) {
return results.sort(() => Math.random() - 0.5)
}

return results
}
Expand Down Expand Up @@ -217,6 +220,10 @@ export class DataClass<ClassSchema = {
return this.withQuery({limit: count, page_size: Math.min(this.query.page_size || 500, count)})
}

public inRandomOrder () {
return this.withQuery({random_order: true})
}

/**
* Set order of fetched objects
*
Expand Down
20 changes: 20 additions & 0 deletions packages/lib-js-core/test/unit/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,26 @@ describe('Data', () => {
.list()
.should.become([{id: 1}, {id: 2}])
})

it('should return random ordered list of objects', async () => {
const objects = [...Array(20).keys()].map((key) => {
return {id: key}
})

api
.get(`/v3/instances/${instanceName}/classes/users/objects/`)
.query({page_size: 500, random_order: true}) // eslint-disable-line camelcase
.reply(200, {objects})

return data.users
.inRandomOrder()
.list()
.then((items: any) => {
should(items)
.be.Array()
.not.be.eql(objects)
})
})
})

describe('#count()', () => {
Expand Down