Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Infer label when possible #98

Closed
sindresorhus opened this issue Jun 11, 2018 · 5 comments
Closed

Infer label when possible #98

sindresorhus opened this issue Jun 11, 2018 · 5 comments

Comments

@sindresorhus
Copy link
Owner

sindresorhus commented Jun 11, 2018

Would be nice to infer the .label() when not specified. Can be useful in environments like Node.js or browser non-minified (development).

ow(foo, ow.string.label('foo'));

It feels moot having to define foo twice.

The current way to do this is to parse them from fn.toString(): https://stackoverflow.com/questions/1007981/how-to-get-function-parameter-names-values-dynamically

@sindresorhus
Copy link
Owner Author

I just realized I have a module for this: https://github.com/sindresorhus/fn-args Totally forgot about it.

@SamVerschueren
Copy link
Collaborator

I'm looking into this, but unless I'm totally missing something, it doesn't feel like fn-args would help here. I'm not even sure if it's possible. The reason is that fn-args (or the solution from StackOverflow) returns the parameter names of the function being invoked. Meaning that you can do fnArgs(ow) which returns ['e', 't'] (dist bundle). But what we want is the name of the variable passed in into the invocation of that function which seems a totally different thing.

@SamVerschueren
Copy link
Collaborator

This makes me wonder, how does power-assert do this?

@SamVerschueren
Copy link
Collaborator

I tried using callsites for this

const callsites = require('callsites');
const fs = require('fs');

const ow = function(value, predicate) {
	const site = callsites()[1];

	const line = site.getLineNumber();

	const content = fs.readFileSync(site.getFileName(), 'utf8').split('\n');

	console.log(content[line - 1]);
};

const x = 'foo';
const predicate = {};

ow(x, predicate);

This prints the string ow(x, predicate) where we should be able to strip out x. I was hoping this information was present in the callsite itself, but it isn't. So this solution would only work in Node because it uses fs.readFileSync.

@sindresorhus
Copy link
Owner Author

The above is exactly what we do in AVA too to get a nice output. I think Node.js-only is better than nothing. My main use-case is Node.js anyway. We just have to document it clearly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants