Skip to content

Commit

Permalink
feat(helpers): add matchType
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Sep 21, 2017
1 parent 2abd957 commit 7f5e1e8
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 1 deletion.
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
module.exports = require('./src').Archetype;
module.exports.to = require('./src/to');

module.exports.CastError = require('./src').CastError;
module.exports.matchType = require('./src/helpers/matchType');
module.exports.to = require('./src/to');
24 changes: 24 additions & 0 deletions src/helpers/matchType.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
'use strict';

/**
* Given a mapping from types ('object', 'string', 'boolean', 'undefined',
* 'number', 'symbol', or 'function') to functions, returns a function that
* takes a `value` and replaces it with the return value from the function
* mapped to by `typeof value`.
*
* Example: `matchType({ 'string': JSON.parse })` will return a function that
* takes a value and only calls `JSON.parse()` if that value is a string.
*
* @param {Object} obj Maps from `typeof` value to function
* @return {Function} transforms value based on `typeof`
*/

module.exports = function(obj) {
return function(v) {
const type = typeof v;
if (typeof obj[type] === 'function') {
return obj[type](v);
}
return v;
};
};
34 changes: 34 additions & 0 deletions test/helpers.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';

const assert = require('assert');
const { matchType } = require('../');

describe('matchType', function() {
it('works with JSON.parse()', function() {
const parse = matchType({ string: JSON.parse });

const obj = { hello: 'world' };

// If given a string, will parse it
assert.deepEqual(parse(JSON.stringify(obj)), obj);

// If not, will do nothing
assert.strictEqual(parse(obj), obj);
assert.strictEqual(parse(null), null);
assert.strictEqual(parse(undefined), undefined);
});

it('works with trimming strings', function() {
const trim = matchType({ string: str => str.trim() });

// If given a string, will trim it
assert.equal(trim(' abc '), 'abc');
assert.equal(trim('abc'), 'abc');

// If not, will do nothing
const obj = {};
assert.strictEqual(trim(obj), obj);
assert.strictEqual(trim(null), null);
assert.strictEqual(trim(undefined), undefined);
});
});

0 comments on commit 7f5e1e8

Please sign in to comment.