Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
TypeScript
type Random_Output<ArrayChooseAmount> =
        ArrayChooseAmount extends number ?
            any[]
            :
            any

function Random<Option> ( value:any[]|`${number}-${number}`, options?:{
    ArrayChooseAmount?: Option
} ):Random_Output<Option> {
    switch (typeof value) {
        case "string": {
            const [ min, max ] = value.split("-")

            return Math.max(Math.floor(Math.random() * (Number(max) + 1)) , Number(min))
        } break;

        default: {
            if ((options?.ArrayChooseAmount || 1) === 1) return value[Math.floor(Math.random() * value.length)]

            const ChosenItems = []

            for ( let i = 0 ; i < (options?.ArrayChooseAmount || 1) ; i++ ) {
                const FilteredItems = value.filter(val => !ChosenItems.includes(val))

                if (FilteredItems.length === 0) break;

                ChosenItems.push(FilteredItems[Math.floor(Math.random() * FilteredItems.length)])
            }

            return ChosenItems
        } break;
    }
}

my Random function will return 3 types of output based on the input & the options:
TypeScript
Random("1-10") 
// will output a number between 1 to 10

Random([1,2,3]) 
// will choose ONE element from the array

Random([1,2,3], { ArrayChooseAmount: 2 }) 
// will choose TWO elements from the array
```
here is a picture of the problem:
https://media.discordapp.net/attachments/983940518163656764/983940800272539678/unknown.png

What I have tried:

<pre>so i am using this type to check if `ArrayChooseAmount` was provided in the options
```ts
type Random_Output<ArrayChooseAmount> =
        ArrayChooseAmount extends number ?
            any[]
            :
            any

at this point i dont even know what im doing anymore
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900