Last active
January 22, 2019 15:19
-
-
Save SethVandebrooke/c520ae46fd0b6361351349ab04f8abb7 to your computer and use it in GitHub Desktop.
Get a random int, character from a string, item from an array, key or value from an object, or any value between two given ints.
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
function random(a, b) { | |
if(Array.isArray(a)){ | |
return a[random(a.length)]; | |
} | |
if (typeof a === "object") { | |
var key = random(Object.keys(a)); | |
return b === "key" ? key : b === "both" ? {key:key,value:a[key]} : a[key]; | |
} | |
if (typeof a === "string" && !!a) { | |
return (a.toLowerCase() === "bool") ? (Math.floor(Math.random()*2) == 1) : random(a.split('')); | |
} | |
if (typeof a === "number"){ | |
if(typeof b === "number"){ | |
return random(b-a)+a; | |
} | |
return Math.floor(Math.random()*a); | |
} | |
return false; | |
}; | |
/* | |
random(10) -> 9 | |
random(10) -> 3 | |
random(0,100) -> 48 | |
random(0,100) -> 77 | |
random("bool") -> true | |
random("bool") -> false | |
random("abcdefg") -> "e" | |
random("abcdefg") -> "a" | |
random(["hello", "hi", "hey"]) -> "hi" | |
random(["hello", "hi", "hey"]) -> "hey" | |
random({name:"Seth", friend: "Dan"}) -> "Dan" | |
random({name:"Seth", friend: "Dan"}) -> "Seth" | |
random({name:"Seth", friend: "Dan"}, "key") -> "name" | |
random({name:"Seth", friend: "Dan"}, "key") -> "friend" | |
random({name:"Seth", friend: "Dan"}, "both") -> {key:"name",value:"Seth"} | |
random({name:"Seth", friend: "Dan"}, "both") -> {key:"friend",value:"Dan"} | |
random("") -> false | |
random(undefined) -> false | |
random(false) -> false | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment