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

clean.array: skipping elements #10

Open
IlyaSemenov opened this issue Jan 9, 2019 · 0 comments
Open

clean.array: skipping elements #10

IlyaSemenov opened this issue Jan 9, 2019 · 0 comments

Comments

@IlyaSemenov
Copy link
Owner

Re: #9 (comment) by @tomanagle:

@IlyaSemenov could there also be a clean.skip method? I sometimes want to allow empty arrays for certain values. A skip method should allow me to define the values that I don't ant to be included in the clean function.

Hmm... Please elaborate with the sample imaginary input, desired output and desired API syntax?

Filtering out values in an array is a reasonable use case, but I'm not sure about the particular API.

At the moment you can do that with either a custom cumulative cleaner:

const cleanArrayEvenValues = clean.array({
  element: clean.integer(), // ensure all elements are integers
  clean: values => values.filter(value => value % 2 === 0) // only keep even values
})

cleanArrayEvenValues([1,2,3,4,5,6,7]).then(res => console.log(res)) // [2,4,6]

or you can delegate the decision to element cleaner, return undefined for unwanted values, and filter them out in the cumulative cleaner:

const cleanArrayEvenValues = clean.array({
  element: clean.integer({
    clean: value => value % 2 === 0 ? value : undefined, // return undefined for unwanted values
  }),
  clean: values => values.filter(value => value !== undefined) // skip undefined elements
})

cleanArrayEvenValues([1,2,3,4,5,6,7]).then(res => console.log(res)) // [2,4,6]

this part clean: values => values.filter(value => value !== undefined) seems to be useful in many circumstances and could be extracted to a helper option like clean.array({ skipUndefined: true }).

Thoughts?

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