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

New tag defaultEmpty #218

Open
villelahdenvuo opened this issue Sep 13, 2022 · 0 comments
Open

New tag defaultEmpty #218

villelahdenvuo opened this issue Sep 13, 2022 · 0 comments

Comments

@villelahdenvuo
Copy link

It's very common pattern to want to append a string only if it's not empty, so I made a helper to do that:

function isEmptyValue(value: unknown): boolean {
	return value === undefined ||
		value === null ||
		(typeof value === 'number' && Number.isNaN(value)) ||
		(typeof value === 'object' && Object.keys(value).length === 0) ||
		(typeof value === 'string' && value.trim().length === 0);
}

function defaultEmpty(strings: string[], ...expressions: unknown[]): string {
	if (expressions.some(isEmptyValue)) return '';
	return String.raw({ raw: strings }, ...expressions)
}

Example:

const filters = Math.random() > 0.5 ? '' : `bar = 'baz'`;
`SELECT * FROM foo WHERE bar = 'foo' ${defaultEmpty`OR ${filters}`}`
// -> "SELECT * FROM foo WHERE bar = 'foo' OR bar = 'baz'"
// -> "SELECT * FROM foo WHERE bar = 'foo' "

Better name ideas are welcome.

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

No branches or pull requests

1 participant