Skip to content

Commit

Permalink
feat: 🎸 times() accepts an object too
Browse files Browse the repository at this point in the history
Sometimes you want to use `times` to create a random number of items.
You can now pass an object with the properties `min` and `max`. `times`
will return an array of objects of length between `min` and `max`. The
default values are `0` for `min` and `10` for `max`.

BREAKING CHANGE: 🧨 `times` will throw if you don't pass a number or an object
  • Loading branch information
Gpx committed Apr 1, 2019
1 parent 6ea38cc commit 4cf76c4
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 2 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,15 @@ const colleagues = userFabricator.times(2, { companyId: 5 })
// => [{ id: 5, companyId: 5 }, { id: 6, companyId: 6 }]
```

If you need a random number of items you can pass an object with the properties
`min` and `max`:

```js
userFabricator.times({ max: 5 }) // => a random length from 1 to 5
userFabricator.times({ min: 0, max: 5 }) // => a random length from 0 to 5
userFabricator.times({ min: 0 }) // => a random length from 0 to 10
```

### sequence()

Sometimes it can be useful to have an increasing value for a field, for example
Expand Down
23 changes: 23 additions & 0 deletions __tests__/Fabricator.js
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,28 @@ describe('Fabricator()', () => {
expect(objs.length).toBe(times)
objs.forEach(obj => expect(obj).toEqual({ id: 1, admin: true }))
})

it.each`
min | max
${undefined} | ${10}
${0} | ${10}
${3} | ${undefined}
${5} | ${7}
`(
'should create an array of length between min: $min and max: $max',
({ min = 1, max = 10 }) => {
const user = Fabricator({})
const objs = user.times({ min, max })
expect(objs.length).toBeGreaterThanOrEqual(min)
expect(objs.length).toBeLessThanOrEqual(max)
}
)
})

it.each(['1', true, false, undefined, null, () => {}])(
'should throw if the count is not a number or an object (test with %p)',
count => {
expect(() => Fabricator({}).times(count)).toThrow()
}
)
})
20 changes: 18 additions & 2 deletions src/fabricator.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,26 @@ function Fabricator(model = {}) {

fabricate.extend = (opts = {}) => Fabricator({ ...model, ...opts })

fabricate.times = (count, opts) =>
Array(count)
fabricate.times = (count, opts) => {
let size
switch (typeof count) {
case 'number':
size = count
break
case 'object':
const { min = 1, max = 10 } = count
size = Math.floor(Math.random() * (max - min + 1) + min)
break
default:
throw new Error(
`times expects a number or an object you passed ${typeof count}`
)
}

return Array(size)
.fill(0)
.map(() => fabricate(opts))
}

return fabricate
}
Expand Down

0 comments on commit 4cf76c4

Please sign in to comment.