JavaScript proxy: Simple log function that will proxy an string argument to the console.log()

301 Views Asked by At

I'm new to JavaScript and learning it for a week now. I had applied for an internship in different companies and I was called yesterday for an interview. They asked me some questions and for this one particular question, I had no clue. Can someone provide me the solution or help me clarify this proxy topic.

What is the solution to this Question?

Please write a simple log function that will proxy a string argument to console.log() *

2

There are 2 best solutions below

0
On

If I were asked this question I would understand "that will proxy a string" to mean "that will pass on a string ... in a controlled way". Wikipedia writes about the Proxy pattern:

What problems can the Proxy design pattern solve?

  • The access to an object should be controlled.
  • Additional functionality should be provided when accessing an object.

So in this case you would verify that the argument is a string, or another interpretation could be that you would convert a non-string to string before passing it on to console.log. So I think the following two answers would be OK:

function log(str) {
    if (typeof str !== "string") throw new TypeError("log should not be called with a non-string");
    console.log(str);
}

log("hello");

Or:

function log(str) {
    if (typeof str !== "string") str = JSON.stringify(str);
    console.log(str);
}

log(["an", "array"]);

1
On

**

function log(){
    console.log(...arguments);
}
log("a", "b")

**