Last active
May 8, 2020 16:18
-
-
Save audunolsen/fae7904d07e1f15c3dc1db3a4e633206 to your computer and use it in GitHub Desktop.
Needed a function which could return either a random array item or a random ranged integer or decimal value with ability to control decimal precision.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const random = ({array: a, min, max, decimal = false, decimalPrecision = 2}) => { | |
if (Array.isArray(a)) return a[Math.floor(Math.random() * a.length)]; | |
else if ([min, max].every(n => typeof n === "number")) { | |
min = Math.ceil(min), | |
max = Math.floor(max); | |
let num = Math.floor(Math.random() * (max - min + 1)) + min; | |
if (decimal) num = (num += Math.random() * (.99 - .1) + .1).toFixed(decimalPrecision); | |
return num; | |
} | |
else throw "Invalid arguments for random function"; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
For an order system where I was taked with implementing the design | |
before viable data was availaible. I needed | |
- random past/future dates | |
- random price w/ decimals | |
- random picked delivery method and delivery status | |
*/ | |
const mockupOrder = _ => { | |
const | |
now = new Date(), | |
past = new Date(now.getTime() + (86400000 * -random({min: 1, max: 5}))), | |
future = new Date(now.getTime() + (86400000 * random({min: 1, max: 7}))); | |
return { | |
registeredDate: this.formatDate(past), | |
expectancyDate: this.formatDate(future), | |
deliveryMethod: random({array: this.deliveryMethods}), | |
deliveryStatus: random({array: this.deliveryStatuses}), | |
price: this.formatPrice(random({min: 100, max: 2000, decimal: true})) | |
} | |
} | |
/* some react component… */ | |
this.state = { | |
orders: [...Array(5)].map(_ => this.mockupOrder()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment