conditional-expanders
TypeScript icon, indicating that this package has built-in type declarations

1.0.0 • Public • Published

conditional-expanders

Conditionally expand arrays and objects with an easy to read syntax

NPM JavaScript Style Guide

Install

npm install --save conditional-expanders

Usage

import { IfAdd, IfPush } from 'conditional-expanders'
import { useState } from 'react'

const App = () => {
  const GetFilters = ({
    category,
    price_range,
    sort,
    autoSortPopularity,
    includeRating
  }: any) => ({
    order_by: [
      ...IfPush(sort, { [sort]: IOrder_By.Asc }),
      ...IfPush(autoSortPopularity, { popularity: IOrder_By.Desc })
    ],
    fields: ['name', 'price', ...IfPush(includeRating, 'rating')],
    where: {
      _and: {
        ...IfAdd(category, { category_id: category }),
        ...IfAdd(price_range, {
          price_retail_base: {
            _gte: +price_range.from,
            _lte: +price_range.to || 10000
          }
        })
      }
    }
  })

  return (
    <MyApp>
      <AmazingQuery filters={GetFilters()} />
    </MyApp>
  )
}

Without conditional expanders

import { IfAdd, IfPush } from 'conditional-expanders'
import { useState } from 'react'

const App = () => {
  const GetFilters = ({
    category,
    price_range,
    sort,
    autoSortPopularity,
    includeRating
  }: any) => ({
    order_by: [
      ...(sort ? [{ [sort]: IOrder_By.Asc }] : []),
      ...(autoSortPopularity ? { popularity: IOrder_By.Desc } : {})
    ],
    fields: ['name', 'price', ...(includeRating ? ['rating'] : [])],
    where: {
      _and: {
        ...(category ? { category_id: category } : {}),
        ...(price_range
          ? {
              price_retail_base: {
                _gte: +price_range.from,
                _lte: +price_range.to || 10000
              }
            }
          : {})
      }
    }
  })

  return (
    <MyApp>
      <AmazingQuery filters={GetFilters()} />
    </MyApp>
  )
}

License

MIT © ighormartins

Readme

Keywords

none

Package Sidebar

Install

npm i conditional-expanders

Weekly Downloads

0

Version

1.0.0

License

MIT

Unpacked Size

6.08 kB

Total Files

11

Last publish

Collaborators

  • ighormartins