Giter VIP home page Giter VIP logo

defaultvalue's Introduction

defaultValue

Helper function to return a default value when the provided value is not defined

A menudo sucede que un valor puede no estar definido y al intentar acceder a una de sus propiedades javascript da error

Esta utilidad previene el problema, devolviendo además un valor seguro en caso de fallar, veamos un ejemplo:

const itemList = {
    creationDate: '03-07-2020',
    creator: 'John Foo',
    collection: [
        {id: 1, value: 10},
        {id: 2, value: 20},
    ]
}

Para acceder a collection, normalmente hacemos lo siguiente:

const collection = itemList.collection

Esto puede fallar si itemList no existe o si itemList.collection no existe, así que para hacerlo de forma segura:

const collection = itemList && itemList.collection

La situación crece a medida que la profundidad del objeto se incrementa y más en el caso de querer devolver un valor por defecto:

const firstItemValue = itemList &&
                       itemList.collection && 
                       itemList.collection.length > 0 &&
                       itemList.collection[0].value ||
                       -1

La función defaultValue lo resuelve devolviendo undefined por defecto o un valor opcional que definamos como tercer parámetro

const firstItemValue = defaultValue('collection.0.value', itemList, -1)

defaultvalue's People

Contributors

aqrojo avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.