npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

giftbox

v0.5.1

Published

A lightweight Javascript library for the Option monad

Downloads

9

Readme

giftbox Build Status

A lightweight Javascript library for the Option monad. Maybe there's something in it, maybe there isn't ;)

$ npm install giftbox
var Option = require('giftbox').Option;

Option('hello world');					// Some
Option(undefined);						// None
Option('hello world').get();			// 'hello world'
Option(null).getOrElse('pied piper');	// 'pier piper'

Giftbox aims to provide a wrapper API around absent values and is highly motivated by Scala's Option.

One of big source of bugs in production environments is missing data represented by nulls, undefined, empty strings, etc. Traditionally calling methods on null or 'empty' values causes NPE's, etc. and forces developers to create disorganized utilities with null/empty checks all over the codebase, adding further complexity.

Overview

Giftbox provides 3 simple classes to handle optional data - Option, Some & None. Here's how to use them:

Simple Examples

Where Giftbox becomes powerful is when you have some logic that returns data and you need to handle that data:

var userDetails = userFetcher('[email protected]');

if(Option(userDetails).isDefined()) {
	render(userDetails);
}

// A more functional form:
Option(userDetails).map(render);

// Wrap a method return value in Option:
var userFetcher = function(email) {
	return Option(userClient.findByEmail(email));
};

userFetcher('[email protected]').map(render).getOrElse(renderNotFound);

Advanced Examples

Building a user subscription UI

// lets fetch a user
userFetcher('[email protected]');

// then lets fetch their subscription record
userFetcher('[email protected]').map(function(user) {
	return subscriptionFetcher(user.id); // returns Option(subscription)
});

// but what if they have no subscription?
userFetcher('[email protected]').map(function(user) {
	// returns either subscription or message
	subscriptionFetcher(user.id).getOrElse('No Subscriptions Found');
});

// ok lets render what we got
userFetcher('[email protected]').map(function(user) {
	renderUI(subscriptionFetcher(user.id).getOrElse('No Subscriptions Found'));
});

// but what if there was no user?
userFetcher('[email protected]').map(function(user) {
	renderUI(subscriptionFetcher(user.id).getOrElse('No Subscriptions Found'));
}).getOrElse(
	redirectToLoginPage();
);

Finding Player Score

var lookupPlayer = function(id) {
	return userFetcher(id); // returns Option(user)
};

var lookupScore = function(player) {
	return scoreFetcher(player); // returns Option(number)
};

var scoreFilter = function(score) {
	return score > 105
};

showScore(lookupPlayer(1).map(lookupScore));
=> Some(Some(103))

// we don't want to render 'Some(103)'
showScore(lookupPlayer(1).flatMap(lookupScore));
=> Some(103)

// great, but we only want to show the score if it is above 105
showScore(lookupPlayer(1).flatMap(lookupScore).filter(scoreFilter));
=> None

// but lets show a default value if player not found or 
// score not found or score not above 105
showScore(
	lookupPlayer(1)
		.flatMap(lookupScore)
		.filter(scoreFilter)
		.getOrElse('Lets start a new game here!')
);
=> 'Lets start a new game here!'

API

Giftbox considers the following "absent" or "empty": null, undefined and NaN.

isDefined

Returns true if the val is not empty.

Option(val).isDefined();
get

Returns val (whether or not it's empty).

Option(val).get();
getOrElse

Returns val if it isDefined otherwise returns elseval.

Option(val).getOrElse(elseVal);
orElse

Returns val if it isDefined otherwise uses alternative as an Option provider.

Option(val).orElse(alternative);
orNull

Returns val if it isDefined otherwise returns null.

Option(val).orNull(alternative);
map

Maps val if it isDefined using the callback function and returns Some(callback(val)) else returns None;

Option(val).map(callback);
flatMap

Flattens nested mapping calls over val if it isDefined using the callback function and returns Some else returns None;

Option(val).flatMap(function(v1) {
	return Option(modify1(v)).flatMap(function(v2) {
		return Option(modify2(v2));
	}
});
filter

Applies predicate to val if it isDefined and returns Some(val) if it passes and None if it fails.

Option(val).filter(predicate);
filterNot

Opposite of filter.

Option(val).filterNot(predicate);
foreach

Applies the callback function to val if it isDefined and doesn't return anything.

Option(val).foreach(callback);
match

Applies someCallback on val if it isDefined otherwise applies noneCallback.

Option(val).match(someCallback, noneCallback);
collect

Applies predicate on val if it isDefined and maps val using callback.

Option(val).collect(predicate, callback);
toArray

Transforms option to an array.

Option(val).toArray();

Contribution

Please contribute to Giftbox via GitHub issues. Would be great if all new code is submitted with tests and documentation. Lets discuss features and bugs there as well!