During a React Developer interview, I was asked to make a function. I'm basically new to this and I'm supposed to be able to make this easily, but there's a catch.
Make an array of colors (as strings). Write a function to create a color manager. It should only have methods (and no properties):
● get - returns the color currently selected
● next - switch to the next color
● prev - switch back to the previous color
● reset - return to the original color
Using the function you have made, you can specify a default color. Each color manager should have its own color.
From the tutorials that I learned from, props have always been used. I'm stuck in this case, so any help would be appreciated.
CodePudding user response:
There are several ways to achieve this, and here is one of them. Basically, I have colorManager function which returns an object containing all the methods that you have described. This function has one argument which is the defaultColor parameter. Also, I have added setPalette method, in case we need more flexibility to change the list of pre-defined colors. Below you can also see usage and colsole output of the methods described.
function colorManager(defaultColor) {
let stack = [defaultColor, "red", "green", "blue", "pink"];
let index = 0;
return {
get: function () {
return stack[index];
},
next: function () {
index = 1;
if (index >= stack.length) {
index = 0;
}
return this.get();
},
prev: function () {
index -= 1;
if (index < 0) {
index = stack.length - 1;
}
return this.get();
},
reset: function () {
index = stack.indexOf(defaultColor);
return this.get();
},
setPalette: function(colours) {
stack = [defaultColor, ...colours]
}
};
}
const cm1 = colorManager("purple");
console.log(cm1.get()); // purple
console.log(cm1.next()); // red
console.log(cm1.next()); // green
console.log(cm1.prev()); // red
console.log(cm1.reset()); // purple
