1

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
  • 2
    Strictly speaking "proxy" is a noun and not a verb, so this question is a bit weird. Commented Mar 13, 2021 at 10:23
  • Proxy is basically a something that intercepts an interaction with an underlying function or property and adds some extra logic to the underlying function or property before invoking/changing/returning that value to the caller. This question is quite ambiguous and more explanation is required for a better answer. You should have asked follow up questions regarding this. Commented Mar 14, 2021 at 6:33

2 Answers 2

2

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"]);

Sign up to request clarification or add additional context in comments.

Comments

-1

**

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

**

1 Comment

Your answer maybe what the OP is looking for but, it has no explanation and does not address the fact that you are interpreting proxy as a simple "wrapper" around a function. Add more explanation and check the answer by @trincot to see how to write a good answer to question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.