Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Leonard Martin committed Sep 3, 2014
1 parent 5cc96a9 commit 5dfb07c
Show file tree
Hide file tree
Showing 4 changed files with 102 additions and 0 deletions.
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,25 @@
camelify
========

Turns hyphen-separated object keys or strings into camel-cased versions.

Examples
--------

`npm install camelify`

```javascript
camelify('one-two');
// => 'oneTwo'

camelify({
'first-name': 'John',
'last-name': 'Smith'
});
// => { firstName: 'John', 'lastName': 'Smith' }
```

Tests
-----

`npm test`
21 changes: 21 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function camelifyString(str) {
return str.replace(/\-([a-z]{1})/g, function (a, s) { return s.toUpperCase(); }, 'g');
}

module.exports = function camelify(obj) {
if (typeof obj === 'string') {
return camelifyString(obj);
}
if (typeof obj !== 'object') {
throw new TypeError('argument must be an object');
}
var output = {};
for (var i in obj) {
if (typeof i === 'string') {
output[camelifyString(i)] = obj[i];
} else {
output[i] = obj[i];
}
}
return output;
};
20 changes: 20 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "camelify",
"version": "0.0.1",
"description": "Simple util for mapping an object with hyphen-separated keys to camelCased keys",
"main": "index.js",
"author": "Lenny Martin <[email protected]>",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/lennym/camelify"
},
"scripts": {
"test": "./node_modules/.bin/mocha test/test.js"
},
"dependencies": {},
"devDependencies": {
"chai": "^1.9.1",
"mocha": "^1.21.4"
}
}
38 changes: 38 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
var camelify = require('../index');

require('chai').should();

describe('camelify', function () {

it('maps hyphen-separated object keys to camelCase', function () {
var input = {
'foo-bar': 1,
'baz': 2
};
camelify(input).should.eql({
fooBar: 1,
baz: 2
});
});

it('can handle multiple hyphen separations', function () {
var input = {
'foo-bar-baz': 1
};
camelify(input).should.eql({
fooBarBaz: 1
});
});

it('returns a camelified string if passed a string', function () {
camelify('hyphen-separated').should.equal('hyphenSeparated');
});

it('throws on non-object input', function () {
var fn = function () {
camelify(1);
};
fn.should.throw();
});

});

0 comments on commit 5dfb07c

Please sign in to comment.