Skip to content

50BytesOfJohn/shy-sloth

Repository files navigation

Shy Sloth Minified size npm NPM Coverage

Shy Sloth

This README and library is still in early development stage. Please be aware that some breaking changes can be introduced in future versions. Thank YOU!

TODO: Description

Table of contents

  1. Inspiration
  2. Install
  3. Functions
    1. withDefault

Inspiration

TODO: Inspiration

Install

  1. npm

    npm install shy-sloth
  2. yarn

    yarn add shy-sloth
  3. pnpm

    pnpm add shy-sloth

Functions

TODO: List of functions

withDefault

When promise resolved to undefined, then default value will be used. Remember that default value is actually function that returns default value.

TODO: Describe the reason of using function

Examples:

const promise = async () => undefined

const foo = withDefault(
  promise,
  () => 'DEFAULT_VALUE'
)

await foo() // 'DEFAULT_VALUE'

You can pass arguments to promise like this:

const promise = async (name) => name ? `Hello ${name}` : undefined

const foo = withDefault(
  promise,
  () => "What's your name?"
)

await foo('John') // 'Hello John'
await foo(null) // "What's your name?"

withMappedResult

When promise resolves, the resolved value is used as a key, to get property from provided object.

Examples:

const statusToText = {
  200: 'OK',
  404: 'Not Found'
}

const promise = async (url) => {
  return fetch(url).then(r => r.status)
}

const getTextFromStatus = withMappedResult(
  promise,
  statusToText
)

await getTextFromStatus('https://...') // 'OK'

You can always make use of withDefault and withMappedResult to provide information even when status was not mapped:

const statusToText = {
  200: 'OK',
  404: 'Not Found'
}

const promise = async (url) => {
  return fetch(url).then(r => r.status)
}

const getTextFromStatus = withDefault(
  withMappedResult(promise, statusToText),
  () => "???"
);

// Status: 200
await getTextFromStatus('https://...') // 'OK'

// Status: 201
await getTextFromStatus('https://...') // '???'

Why no built in default value in withMappedResult? Shy-sloth target is to provide as simple as possible functions, that can work well together. You can see how easy was to add withDefault. There were even no changes needed in code. I've just added withDefault on top of withMappedResult.

Let's be honest. If you don't like this approach, the shy sloth, is totally fine with that. He's sleeping anyways. 🦥

License

MIT

Releases

No releases published

Packages

No packages published