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() *

Wenfang Du
  • 8,804
  • 9
  • 59
  • 90
anish
  • 19
  • 4
  • 2
    Strictly speaking "proxy" is a noun and not a verb, so this question is a bit weird. – trincot Mar 13 '21 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. – Abrar Hossain Mar 14 '21 at 06:33

2 Answers2

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"]);
trincot
  • 317,000
  • 35
  • 244
  • 286
-1

**

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

**

Nelson Uprety
  • 77
  • 1
  • 8
  • 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 – Abrar Hossain Mar 14 '21 at 06:36