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

feat(function): tap utility #1

Merged
merged 4 commits into from
Jun 9, 2021
Merged

feat(function): tap utility #1

merged 4 commits into from
Jun 9, 2021

Conversation

innocenzi
Copy link
Sponsor Contributor

@innocenzi innocenzi commented Jun 9, 2021

This PR adds a new utility function, tap. This is a common utility found in ecosystems like Laravel or Ruby. Underscore has an implementation as well.

The concept is fairly simple: you give a value as the first argument to tap, and a callback as the second argument. The callback takes the value as a parameter, and is executed just before tap returns the initial value.

This is useful for avoiding temporary variables:

// Without tap
function createUser(name: string, age: number) {
  const user = new User()
  user.name = name
  user.age = age

  return user
}

// With tap
function createUser(name: string, age: number) {
  return tap(new User, user => {
    user.name = name
    user.age = age
  })
}

This is the first example that came to my mind, and as you can see, the trade-off tap offers to avoid declaring a variable is a little bit of readability. Sometimes, it's better not to use it, but most of the times, I find it super useful.

src/function.test.ts Outdated Show resolved Hide resolved
src/function.ts Outdated Show resolved Hide resolved
@innocenzi
Copy link
Sponsor Contributor Author

I applied the suggestions 👍

@antfu antfu merged commit f48e8b9 into antfu:main Jun 9, 2021
@innocenzi innocenzi deleted the feat/tap branch June 9, 2021 14:17
@innocenzi
Copy link
Sponsor Contributor Author

Thanks Anthony!

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

Successfully merging this pull request may close these issues.

None yet

2 participants