Skip to content

add extract #5317

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

Closed
wants to merge 1 commit into from
Closed

add extract #5317

wants to merge 1 commit into from

Conversation

damianbeles
Copy link

@damianbeles damianbeles commented Nov 22, 2021

Hello 👋. Hope this PR will help many in their software development process.

What is introduced in this PR?

This PR introduces extract function which helps you extract sublists from a given collection and some predicates.

How is extract used?

Let's say we have this array:

const documents = [
  { pages: 24,  type: 'ebook',   category: 'finance', ... },
  { pages: 240, type: 'book',    category: 'self development', ... },
  { pages: 41,  type: 'ebook',   category: 'finance', ... },
  { pages: 66,  type: 'ebook',   category: 'it', ... },
  { pages: 2,   type: 'article', category: 'it', ... }
]

and we want to extract finance ebooks, self development books and documents from it category.

We can do this with extract function I implemented:

const [financeEbooks, selfDevelopmentBooks, itDocuments] = extract(
  documents,
  doc => doc.type === 'ebook' && doc.category === 'finance',
  doc => doc.type === 'book' && doc.category === 'self development',
  doc => doc.category === 'it'
)

Printing these sublists we obtain:

console.log(financeEbooks)
// [ { pages: 24, type: 'ebook', category: 'finance', ... }, { pages: 41, type: 'ebook', category: 'finance', ... }]

console.log(selfDevelopmentBooks)
//  [{ pages: 240, type: 'book', category: 'self development', ... }]

console.log(itDocuments)
//  [{ pages: 66, type: 'ebook', category: 'it', ... }, { pages: 2, type: 'article', category: 'it', ... }]

How would you do this without extract?

const financeEbooks = documents.filter(doc => doc.type === 'ebook' && doc.category === 'finance');
const selfDevelopmentBooks = documents.filter(doc => doc.type === 'book' && doc.category === 'self development');
const itDocuments = documents.filter(doc => doc.category === 'it');

Why the addition of extract?

You won't parse the documents array three times (or N times generally speaking). You'll only parse it once. Also, you'll declare the sublists in the same place, thus making the code easier to read.

@jdalton jdalton closed this Sep 16, 2023
@jdalton jdalton added the issue bankruptcy Closing the issue/PR to start fresh label Sep 16, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
issue bankruptcy Closing the issue/PR to start fresh
Development

Successfully merging this pull request may close these issues.

2 participants