-1

I have this function:

getNewColor(): {} {
    return colors.red;
}

And this object:

colors: any = {
  red: {primary: '#ad2121',secondary: '#FAE3E3'},
  blue: {primary: '#1e90ff',secondary: '#D1E8FF'},
  yellow: {primary: '#e3bc08',secondary: '#FDF1BA'}
};

Every time getNewColor() is being called, a new color from the object should be returned (doesn't matter what color as long it's hasn't been returned before).

If I call:

console.log(getNewColor());
console.log(getNewColor());
console.log(getNewColor());

The output should be:

{primary: '#ad2121',secondary: '#FAE3E3'}
{primary: '#e3bc08',secondary: '#FDF1BA'}
{primary: '#1e90ff',secondary: '#D1E8FF'}

What is the best way to implement getNewColor()?

Hila Grossbard
  • 521
  • 7
  • 20
  • `getNewColor(color: string): any { return colors[color] }`? And you could use it as `getNewColor('red')`, `getNewColor('blue')` and `getNewColor('yellow')`. Or do you want to return a random color every time the function is called? – ruth Nov 23 '20 at 12:06
  • What do you mean: the order does not matter? Maybe you meant: the color does not matter? – captain-yossarian from Ukraine Nov 23 '20 at 12:06
  • 1
    @captain-yossarian yes, this is what i meant. – Hila Grossbard Nov 23 '20 at 12:08
  • 1
    @MichaelD this might not work, since i don't know the colors in my object, all I know is that I need it to give me some color it didn't gave before. – Hila Grossbard Nov 23 '20 at 12:11
  • @HilaGrossbard: So you want to randomly return a color object from the function? – ruth Nov 23 '20 at 12:12
  • 1
    Your question lacks an attempt of what you're trying to do aswell as clarification whether the color should be random or/and should `never` return the same color. –  Nov 23 '20 at 12:12
  • 1
    @MichaelD exactly, random and different. – Hila Grossbard Nov 23 '20 at 12:14
  • Random property from an object is already answered here: https://stackoverflow.com/q/2532218/6513921. But the _"different"_ needs further clarification. How and relative to which context is it supposed to be different? What if the function is called from different places, should each get exclusive responses? – ruth Nov 23 '20 at 12:17
  • 2
    If it's random and different, what should happen on the 4th call to the function? – Evan Trimboli Nov 23 '20 at 12:17
  • 1
    @EvanTrimboli the times the function getNewColor() is being asked cant be bigger than the amount of colors. – Hila Grossbard Nov 23 '20 at 12:26

1 Answers1

2

Here is your solution:

colors = {
  red: {primary: '#ad2121',secondary: '#FAE3E3'},
  blue: {primary: '#1e90ff',secondary: '#D1E8FF'},
  yellow: {primary: '#e3bc08',secondary: '#FDF1BA'}
};

const getColor=()=>{
    const keys = Object.keys(colors);
    const key = Math.floor(Math.random() * keys.length);
    return colors[keys[key]]
}

But I agree, that your question lacks of any attempts