Coercive
Coercive is a JavaScript toolkit for writing type coercions: functions that parse strings into other formats with configurable defaults if the string can't be parsed. Object coercion functions can be used to clean up data (from CSV, or other string-based formats) by coercing strings into numbers, dates, and more.
Examples
Coercive provides functions for coercing both individual values and keys of objects. Here are some examples:
// coerce a number or return zero if the result is NaNvar numOrZero = coerce; // 42 // 0 var intOrNull = coerce; // 42 // null // coerce the "size" key of an object to a float (in place)var sizeToFloat = coerceobject ;; // {"size": 46.5} // coerce a date string into a Date object:var parseDate = coerce; // <Date> // null // you can also create multi-format date coercions, e.g. if your// data contains messy data in multiple formatsvar parseDate = coerce; // <Date> // <Date> // object coercions have a .map() method, too, just in case// you don't want to modify the objects in placevar a = size: "1.4" b = size: "2.6";a b;// produces an array of new objects with coerced keys:// [{"size": 1.4}, {"size": 2.6}] // and you can coerce multiple keys like this:var prepData = coerceobject ;;// produces:// {"height": 6.5, "weight": 250, "birthday": <Date>}// or, just apply your coersions to a list of data objects,// e.g. loaded from a CSV file:d3;
Usage (Node.js)
To use coercive in Node.js:
$ npm install coercive
then, in your script:
var coerce = ;
Usage (browser)
To use coercive in your browser, just include the script:
<!-- and, if you're using coerce.date(), be sure to include d3 -->
This gives you the coercive API in the coerce
object (not coercive
!).