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

castjs

v0.0.1

Published

Validation and conversion library

Downloads

107

Readme

cast.js

The cast.js library was written to provide convenient methods for validating and converting object properties for model based frameworks like backbone.js. The core provides several features to make converting, validating, and error handling easier:

  • Convert object properties in place (by passing an object and property name)
  • Validate object properties without converting (by passing a value only)
  • Handle various data states at any point (blank, valid, invalid, out of range)

Syntax

The syntax was designed to be human readable. See the Module API for complete documentation of built in modules.


  cast(obj, 'propName').as.a.dataType() // converts value in place
  cast(value).is.a.dataType().valid // returns true if value is valid for that data type

  // Note: is/as/a/an are optional.

Here are some real-world examples:


  cast(attrs, 'start_date').date().beginningOfDay()
  cast(attrs, 'email').email()
  if (cast(age).integer().atLeast(13).valid) {
    // do something
  }

State Handlers

The if method allows you run callback functions based on the current state (blank, valid, out of range, or invalid). Usually this is done at the end of a method chain, but it can be done any time after the initial data type is cast.


  cast(attrs, 'foo').as.an.integer().atLeast(1).noMoreThan(bar).if({
    blank: function() { showError('foo', 'foo is required') },
    valid: function() { console.log('foo is valid') },
    outOfRange: function() { showError('foo', 'foo must be at least 1 and no more than ' + bar + '.') },
    invalid: function() { showError('foo', 'foo is not a whole number.') }
  })

Note: States are evaulated in the order shown here. If a given state is true and a handler was provided, only the handler for that state will be called. If a state is true, but no handler was provided, the next state will be evaluated.

Creating Custom Modules

Registering your Module

You can add you own custom modules using the cast.register method. All modules must provide an initialize method at the very least. cast.register can be called in two ways:


  cast.register('myModule', function(arg1, arg2){ ... }) // For simple modules with no chained methods
  cast.register({ // For multiple modules or modules with chaining
    myModule: {
      initialize: function(arg1, arg2){ ... }, // initialize is called by cast(value).myModule()
      methodOne: function(arg1, arg2){ ... },
      methodTwo: function(arg1, arg2){ ... }
    }
  })

Note: an unregister method is also provided for testing purposes: cast.unregister('moduleOne', 'ModuleTwo', ...)

Aliases

You can add aliases for you modules or module methods by including the alias/method mapping in your module definition:


  cast.register({
    moduleName: {
      initialize: function(){ ... },
      methodName: function(){ ... },
      methodAlias: 'methodName'
    },
    moduleAlias: 'moduleName'
  })

Setting the State

All of the methods in you module will change the state of the cast in some way or another. There are three built in helpers: set, fail, and rangeError. Here is an example of how they could be used:


  cast.register('positiveInteger', function(x) {
    x = parseInt(x, 10)
    if (isNaN(x)) return this.fail()
    if (x <= 0) return this.rangeError()
    this.set(x)
  })

Built-in Helpers

Custom modules have access to a handfull of useful helpers for parsing data. You can use these from within you module methods by calling this.helperName(x).

  • makeType(x) converts x to a the same data type as the module by running it's initialize function and returning the value.
  • makeString(x) converts x to a string if it can, or falls back to an empty string.
  • makeNumber(x,d) parses x as a number, optionally to d decimal places or returns NaN.
  • realTypeof(x) returns the actual type of x. Includes support for arrays and date objects.
  • trimString(x) removes the leading and trailing whitespace from single line strings. Multi-line strings are not changed.
  • isBlank(x) returns true if x is null, undefined or an empty string.
  • isValid(x) returns false if x is null, undefined, NaN or InvalidDate.