-1

I have a function like so:

const ILog = <T>(value: T): T => {
  console.log(value);
  return value;
}

It acts like console.log with the added benefit that it keeps the value it had.

However, I'd like to differenciate between calls of the same function:

let a = false;
let b = false;
let c = false;

ILog(a);
ILog(b);
ILog(c);

// current
$ node file.js
false
false
false

// expected
$ node file.js
ILog(a): false
ILog(b): false
ILog(c): false

Can some javascript black magic achieve this?

An example of how this would work would be like this:

const ILog = (name: string) => <T>(value: T): T => {
  console.log(`ILog(${name})`, value);
  return value;
}

ILog("[some_expression]")([some_expression]);

$ node file.js
ILog([some_expression]): [result]

Without repeating the expression in string form.

  • So you want the function to print the syntax it was called with? I'm not aware of any js tools to do that short of some silliness with `eval()`, but it wouldn't be called like `ILog(a)` anymore. – CollinD Oct 12 '22 at 16:42
  • I wouldn't mind changing the name :V – Carlo Augusto Bagnoli Gomez Oct 12 '22 at 16:46
  • Would it be sufficient for you to use a [stack trace](https://stackoverflow.com/q/591857/1426891)? It's more verbose, but a call to `console.trace()` or a light processing of `new Error().stack` might give you the context you need to differentiate between calls. – Jeff Bowman Oct 12 '22 at 17:42

1 Answers1

0

There's no magic way to do this, you could do something like this if you really wanted:

const ILog = <T>(value: T, argumentName: string): T => {
  console.log(`ILog(${argumentName}): ${value}`);
  return value;
}

const a = false;
ILog(a, "a");

Or using your existing ILog function,

ILog(`ILog(a): ${a}`);
CollinD
  • 7,304
  • 2
  • 22
  • 45
  • The first one is kinda what I've been doing, I posted this question cause I might learn smth new idk. – Carlo Augusto Bagnoli Gomez Oct 12 '22 at 17:02
  • The second one wouldn't really work tho, it doesn't keep the original value intact – Carlo Augusto Bagnoli Gomez Oct 12 '22 at 17:02
  • Like I said, there's no magic. Only the code at the original calling location can possibly be aware of the variable name. – CollinD Oct 12 '22 at 17:03
  • Also the main reason why I wanted to see a better way is bc some arguments can be convoluted like `ILog(!!a)` or `ILog(a.some(({ status }) => status === "smth")))` – Carlo Augusto Bagnoli Gomez Oct 12 '22 at 17:04
  • Regardless, `ILog` only gets a value. JS is pass-by-value, the `ILog` function sees no difference between `ILog(a.some(...))` and `ILog(false)`. The `ILog` function also does its own logging, which precludes another function from logging to the line before `ILog` does, so you literally cannot generate the output you want with a function that does its own call to `console.log` as every call to `console.log` creates a newline. – CollinD Oct 12 '22 at 17:06