How to convert Javascript Array to array of functions?

  • A+
Category:Languages

I had a question in my interview where they asked me to transform an array to array of functions like below:

var a = ["a", 24, { foo: "bar" }]; var b = transform(a);  console.log(a[1]); // 24 console.log(b[1]()); // 24 

I tried many combinations but I couldn't really do what they ask. Can someone tell me how to implement the transform function?

 


I'm not exactly sure about their intention, but a simple approach to provide the given results would be as follows:

function transform(a){   return a.map( (el) => () => el ); } 

PS: the interesting follow up question would then be about the differences between the results for b[0]() and b[1]() compared to b[2]() and how to mitigate the problems that might arise for the later.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: