GithubHelp home page GithubHelp logo

sindresorhus / camelcase Goto Github PK

View Code? Open in Web Editor NEW
660.0 14.0 95.0 79 KB

Convert a dash/dot/underscore/space separated string to camelCase: foo-bar → fooBar

License: MIT License

JavaScript 96.50% TypeScript 3.50%

camelcase's Introduction

camelcase

Convert a dash/dot/underscore/space separated string to camelCase or PascalCase: foo-barfooBar

Correctly handles Unicode strings.

If you use this on untrusted user input, don't forget to limit the length to something reasonable.

Install

npm install camelcase

Usage

import camelCase from 'camelcase';

camelCase('foo-bar');
//=> 'fooBar'

camelCase('foo_bar');
//=> 'fooBar'

camelCase('Foo-Bar');
//=> 'fooBar'

camelCase('розовый_пушистый_единорог');
//=> 'розовыйПушистыйЕдинорог'

camelCase('foo bar');
//=> 'fooBar'

console.log(process.argv[3]);
//=> '--foo-bar'
camelCase(process.argv[3]);
//=> 'fooBar'

camelCase(['foo', 'bar']);
//=> 'fooBar'

camelCase(['__foo__', '--bar']);
//=> 'fooBar'

API

camelCase(input, options?)

input

Type: string | string[]

The string to convert to camel case.

options

Type: object

pascalCase

Type: boolean
Default: false

Uppercase the first character: foo-barFooBar

import camelCase from 'camelcase';

camelCase('foo-bar', {pascalCase: true});
//=> 'FooBar'

camelCase('foo-bar', {pascalCase: false});
//=> 'fooBar'
preserveConsecutiveUppercase

Type: boolean
Default: false

Preserve consecutive uppercase characters: foo-BARFooBAR

import camelCase from 'camelcase';

camelCase('foo-BAR', {preserveConsecutiveUppercase: true});
//=> 'fooBAR'

camelCase('foo-BAR', {preserveConsecutiveUppercase: false});
//=> 'fooBar'
locale

Type: false | string | string[]
Default: The host environment’s current locale.

The locale parameter indicates the locale to be used to convert to upper/lower case according to any locale-specific case mappings. If multiple locales are given in an array, the best available locale is used.

import camelCase from 'camelcase';

camelCase('lorem-ipsum', {locale: 'en-US'});
//=> 'loremIpsum'

camelCase('lorem-ipsum', {locale: 'tr-TR'});
//=> 'loremİpsum'

camelCase('lorem-ipsum', {locale: ['en-US', 'en-GB']});
//=> 'loremIpsum'

camelCase('lorem-ipsum', {locale: ['tr', 'TR', 'tr-TR']});
//=> 'loremİpsum'

Setting locale: false ignores the platform locale and uses the Unicode Default Case Conversion algorithm:

import camelCase from 'camelcase';

// On a platform with `tr-TR`.

camelCase('lorem-ipsum');
//=> 'loremİpsum'

camelCase('lorem-ipsum', {locale: false});
//=> 'loremIpsum'

Related

camelcase's People

Contributors

ambujsahu81 avatar bendingbender avatar coreyfarrell avatar danielseehausen avatar davidepastore avatar dcousens avatar fdawgs avatar forresst avatar jcrandall101 avatar jhnns avatar kevva avatar lokua avatar mesaugat avatar nam-hle avatar ntwb avatar pedromiguelss avatar qix- avatar qw-in avatar rasgele avatar rocktimsaikia avatar samverschueren avatar semigradsky avatar sindresorhus avatar skavigitp avatar stringparser avatar sverweij avatar tychenjiajun avatar yuler avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

camelcase's Issues

ts-jest encountered an unexpected token with camelcase

After version 7, camelcase uses export default to export the camelCase function. This change causes Jest failed to run.

To reproduce:

package.json

{
  "name": "a",
  "version": "0.0.0",
  "scripts": {
    "test": "jest"
  },
  "devDependencies": {
    "@types/jest": "^29.2.4",
    "jest": "^29.3.1",
    "ts-jest": "^29.0.3",
    "typescript": "^4.9.4"
  },
  "dependencies": {
    "camelcase": "^7.0.1"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "commonjs", 
    "rootDir": "./src",                     
    "moduleResolution": "node",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
  }
}

jest.config.json

{
    "preset": "ts-jest",
    "testEnvironment": "node"
}

src/lib.ts

import camelcase from 'camelcase';

export const f = () => {
    return camelcase('a-b');
};

tests/tests.test.ts

import { f } from '../src/lib'

it("should success", () => {
    expect(f()).toBe('aB');
});

Run npm i and run npm test. The result is

$ npm test

> [email protected] test
> jest

 FAIL  tests/test.test.ts
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

I would like to know a good way to solve this.

Breaking with IE11

I'm really sorry to say this, but the library is not working with IE11 because of index.js has ECMAScript format, and a fat arrow is breaking our build. We need to develop for IE11 because is a client requirement, so, how can we solve this problem? Could you please upload the library transpiled?

Thanks in advanced.

"Invalid regular expression: /[\p{Lu}]/: Invalid escape" after updating to version 6.2.1

Hello,

just FYI, it seems like version 6.2.1 broke css-loader that was working perfectly fine using NodeJS v8.
And yes, I understand that both libraries require node v10+, but it was working perfectly fine.

My build started to fail with this error "Invalid regular expression: /[\p{Lu}]/: Invalid escape" and after a while, I found your library as css-loader's dependency that has been updated from version 6.2.0 to 6.2.1

Updating NodeJS version fixed the issue, but still this is something that shouldn't happen as a minor patch :)

This issue is created for the people who will encounter the same problem, hope this helps

Symbols are prepended with dash

I am not sure whether this is in the scope of this project but I noticed that in some cases symbols are prepended with a dash where I expected them to stay the same or to be deleted.

Example tests:

test('camelCase', t => {
        t.is(fn('foo bar?'), 'fooBar?');  // or 'fooBar'
        t.is(fn('foo bar!'), 'fooBar!');
        t.is(fn('foo bar$'), 'fooBar$');
        t.is(fn('foo-bar#'), 'fooBar#');
});

Camelcase output:

"fooBar-?"
"fooBar-!" 
"foo- $bar"
"fooBar-#"

preserveCamelCase malfunctions on "A::a"

> const camelcase = require("camelcase");
undefined
> camelcase("A::a");
"a:-:a"
> camelcase("A::a",{pascalCase:true});
"A:-:a"

I'm not saying this would be common in the wild, but this is nonetheless a surprising behavior.

Note that c.toLowerCase() === c and c.toUpperCase() === c both evaluates to true when c does not contain any alphabets.

Must use import to load ES Module

Hello,
I tried to use camelCase as below, but I got ES Module Error like below.
Would you tell me how to solve this?

Error Log

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/jin.park/Documents/asurion-github/korea-nestjs-job-prototype/node_modules/camelcase/index.js
require() of ES modules is not supported.
require() of /Users/jin.park/Documents/asurion-github/korea-nestjs-job-prototype/node_modules/camelcase/index.js from /Users/jin.park/Documents/asurion-github/korea-nestjs-job-prototype/dist/user/UserService.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/jin.park/Documents/asurion-github/korea-nestjs-job-prototype/node_modules/camelcase/package.json.

To reproduce:

package.json

{
  "name": "korea-nestjs-job",
  "version": "0.0.1",
  "description": "",
  "author": "",
  "private": true,
  "license": "UNLICENSED",
  "scripts": {
    "prebuild": "rimraf dist",
    "build": "nest build",
    "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
    "start": "nest start",
    "dev:uat": "nest start --watch",
    "start:dev": "nest start --watch",
    "start:debug": "nest start --debug --watch",
    "start:prod": "node dist/main",
    "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
    "test": "jest",
    "test:watch": "jest --watch",
    "test:cov": "jest --coverage",
    "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
    "test:e2e": "jest --config ./test/jest-e2e.json"
  },
  "dependencies": {
    "@asurion/dataprotection-voltage-node": "^3.0.0",
    "@nestjs/common": "^8.1.1",
    "@nestjs/config": "^1.0.2",
    "@nestjs/core": "^8.1.1",
    "@nestjs/platform-express": "^8.1.1",
    "@nestjs/swagger": "^5.1.1",
    "@types/validator": "^13.7.11",
    "asurion-uuid": "git+https://github.com/asurion-private/web-asurion-uuid.git",
    "aws-sdk": "^2.1292.0",
    "bluebird": "^3.4.6",
    "camelcase": "^7.0.1",
    "class-transformer": "^0.5.1",
    "class-validator": "^0.13.2",
    "mysql2": "^2.3.3",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^7.1.0",
    "swagger-ui-express": "^4.1.6",
    "wp-commonmodels-v2": "git+https://github.com/asurion-private/web-wp-commonmodels-v2.git",
    "wp-config": "git+https://github.com/asurion-private/web-wp-config.git",
    "wp-ds": "git+https://github.com/asurion-private/web-wp-ds.git",
    "wp-ds-mysql": "git+https://github.com/asurion-private/web-wp-ds-mysql.git",
    "wp-ds-sql": "git+https://github.com/asurion-private/web-wp-ds-sql.git",
    "wp-logging": "git+https://github.com/asurion-private/web-wp-logging.git",
    "wp-service-http": "git+https://github.com/asurion-private/web-wp-service-http.git",
    "wp-service-redis": "git+https://github.com/asurion-private/web-wp-service-redis.git"
  },
  "devDependencies": {
    "@nestjs/cli": "^7.6.0",
    "@nestjs/schematics": "^7.3.0",
    "@nestjs/testing": "^8.1.1",
    "@types/express": "^4.17.11",
    "@types/jest": "^26.0.22",
    "@types/node": "^14.14.36",
    "@types/supertest": "^2.0.10",
    "@typescript-eslint/eslint-plugin": "^4.19.0",
    "@typescript-eslint/parser": "^4.19.0",
    "eslint": "^7.22.0",
    "eslint-config-prettier": "^8.1.0",
    "eslint-plugin-prettier": "^3.3.1",
    "jest": "^26.6.3",
    "lint-staged": "^13.1.0",
    "prettier": "^2.2.1",
    "supertest": "^6.1.3",
    "ts-jest": "^26.5.4",
    "ts-loader": "^8.0.18",
    "ts-node": "^9.1.1",
    "tsconfig-paths": "^3.9.0",
    "typescript": "^4.2.3"
  },
  "jest": {
    "moduleFileExtensions": [
      "js",
      "json",
      "ts"
    ],
    "rootDir": "src",
    "testRegex": ".*\\.spec\\.ts$",
    "transform": {
      "^.+\\.(t|j)s$": "ts-jest"
    },
    "collectCoverageFrom": [
      "**/*.(t|j)s"
    ],
    "coverageDirectory": "../coverage",
    "testEnvironment": "node"
  }
}

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2020",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": "./",
    "incremental": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "resolveJsonModule": true,
    "esModuleInterop": true
  }
}

UserService.ts

import camelCase from 'camelcase';

    Object.keys(requestAssetDto).map(key => {
      console.log(key);
      console.log('pasacal:', camelCase(key, { pascalCase: true }));
      return key;
    });

c('e2e')

Seems like the regression fix to #53 creates another regression

5.3.0:

camelcase('e2e') === 'e2e';

5.3.1:

camelcase('e2e') === 'e2E';

Using `let` limits browser and node support

This commit (2296030) replaces var with let for ES2015 style. However, the let syntax is not widely supported, and breaks with some toolsets, such as uglify.

This could be resolved by:

  • Reverting to supported syntax of var, or
  • Transpile the npm published version to ES5.

c('Hello1World')

Seems like the fix to #42 changes the behavior of identifying word breaks after numbers:

Pre 5.3.0:

camelcase('Hello1World') === 'hello1World'

5.3.0:

camelcase('Hello1World') === 'hello1world';

I guess it's a matter of opinion, but the previous behavior does seem more like what people would expect. At any rate, if this is the intended behavior, I would have preferred a major version bump.

Fail on minify

My project fail to build while uglifyjs try to minify camelcase module, case you use let instead of val

invalid expression error

I am getting the following error with latest version:
"camelcase": "^6.0.0",

this is my usage
const functionName = camelCase(file.slice(0, -5).split("/").join("_"));

Detailed stack trace: SyntaxError: Invalid regular expression: /[\p{Lu}]/: Invalid escape
    at preserveCamelCase (/srv/node_modules/camelcase/index.js:11:3)
    at camelCase (/srv/node_modules/camelcase/index.js:63:11)
    at Object.<anonymous> (/srv/index.js:24:24)
    at Module._compile (module.js:653:30)
    at Object.Module._extensions..js (module.js:664:10)
    at Module.load (module.js:566:32)
    at tryModuleLoad (module.js:506:12)
    at Function.Module._load (module.js:498:3)
    at Module.require (module.js:597:17)
    at require (internal/module.js:11:18)

'SyntaxError: invalid identity escape in regular expression' in Firefox after upgrading to v6.0.0

I get this error in Firefox only:
SyntaxError: invalid identity escape in regular expression
though in Chrome it works okay.
image

Steps to reproduce:

git clone https://github.com/apasov/animatable-properties.git
cd animatable-properties
git reset --hard 3728a084984482ddcfc6a096a38c9b4c10a8c270

then open index.html in Firefox and you'll see blank page and the error in console.

After this commit fix: downgrade to camelcase v5.3.1 to fix syntax error in Firefox which fixes the error

git reset --hard cd3bda8f6a5972e7af4a71c5b65a3616c2852b01

reload index.html and it works as intended without errors

Move regexes to the outer scope

They will need descriptive variables.

See: #85 There was no proof there that it actually improves performance, but I'm willing to do it if only for readability.

Case conversion with specific locale

Case conversion are done with String.prototype.toLocaleLowerCase() and String.prototype.toLocaleUpperCase() without explicit locale parameter and this causes host dependent output.
Example:

camelCase('lorem-ipsum')
//=> 'loremIpsum' if host locale is en-US
//=> 'loremİpsum' if host locale is tr-TR

This causes unexpected results int hosts with non en-US environment.

I'd suggest to extend options parameter to have a locale property to be passed to aforementioned methods.

camelCase('lorem-ipsum', {locale: 'en-US'});
//=> 'loremIpsum' if host locale is en-US
//=> 'loremIpsum' if host locale is tr-TR

UglifyJS issue

While building a meteor app, I got this error

UglifyJS minification error:

SyntaxError: Unexpected token: name (isLastCharLower) at
node_modules/camelcase/index.js line 4

It seems odd to me that this line would throw an error, but here we are.

Edge cases

> camelCase('', '')
'-'
> camelCase(' ')
TypeError: Cannot read property 'toLowerCase' of undefined

I think it should return an empty string in both cases.

Add notification for "node.js only" support

I had the very similar issue like some guys before, that i assumed this package is valid also for frontend scripts. After figuring out, why the code is not running on ie11, i found out, that your package is not transpiled. That's totally fine. But please add an appropriate info text within the description, that this package is written mainly for node.js. You can't demand the reading of the source code from every user. This "bug/unexpected behavior" was really not obvious. So please add the note for future usage. :)

Default exports vs module.exports = ...

Regarding this comment:

camelcase/index.js

Lines 78 to 79 in 7501406

// TODO: Remove this for the next major release
module.exports.default = camelCase;

It seems that this way of importing camelcase:

import camelCase from 'camelcase';

is deprecated in favour of:

import camelCase = require('camelcase');

I'm strongly opposed to this, since the second is not in JavaScript standard. (require is a CommonJS syntax?)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

Please take a look and let me know what do you think about this.

NPM is not updated with the latest version

Hello there,

I installed the NPM package on my code and TS was complaining preserveConsecutiveUppercase was not one of the possible options and indeed, it's not in the d.ts file.

I forked the code to add it and make a pull request and then found out it's already (both preserveConsecutiveUppercase and locale) there, but the version on NPM doesn't have it yet.

Would you please publish this version that both the other options are set in the description?

Thanks!

Incorrect behaviour with numbers

Hello
My code received object from API and do not know its format.
Even I got already camecased object, it capitalises "C", but should not.
camelcaseKeys({"i2cTapSensor": "value"});
{ i2CTapSensor: 'value' }

As a workaround, added the key to exclusion:
{exclude: ["i2cTapSensor"]}

Throws error in Internet Explorer 11

I'm using this module in a Meteor project and when it's inquired, it causes first a syntax error here and then an unrecognized character error here when the arrow functions are replaced with ES5 functions.

Error in Index.js in 6.0.0 version

`node_modules/assets-webpack-plugin/node_modules/camelcase/index.js:38
[ERROR] 		...{pascalCase: false},
[ERROR] 		^^^
[ERROR] SyntaxError: Unexpected token ...`

Am experiencing an issue in index.js file. I have comitted the changes.

Build break with camelcase 6.0.0

I'm seeing this build break:
/app/node_modules/camelcase/index.js:69
.replace(/[.- ]+([\p{Alpha}\p{N}]|$)/gu, (_, p1) => p1.toLocaleUpperCase())

SyntaxError: Invalid regular expression: /[.- ]+([\p{Alpha}\p{N}]|$)/: Invalid escape
at camelCase (/app/node_modules/camelcase/index.js:69:3)
at getAssetKind (/app/node_modules/assets-webpack-plugin/dist/lib/getAssetKind.js:9:10)
at /app/node_modules/assets-webpack-plugin/dist/index.js:93:26
at Array.reduce ()
at /app/node_modules/assets-webpack-plugin/dist/index.js:87:30
at Array.reduce ()
at Compiler.afterEmit (/app/node_modules/assets-webpack-plugin/dist/index.js:74:27)

I'm using node 8.11.4 to build.

Correctly handle Unicode characters

The regular expressions in this package don’t support unicode characters such as àçéèù so camelCase("Licorne époustouflante") outputs licorne époustouflante.

Perhaps we could add a transliterate option that leverages transliterate so camelCase("Licorne époustouflante", { transliterate: true }) outputs licorneEpoustouflante.

Another slightly more complicated alternative would be to have camelCase("Licorne époustouflante", { transliterate: true }) output licorneÉpoustouflante.

What do you think? I could put a PR together.

treating none alphabetic characters

I'm using camelcase to deal with css class names.
I'd like to transform css classes like m-grid-col6@md to camelCase notation mGridCol6@md and it works perfectly, but sometime I got input already camelCased(its due to React and its props) and it transform into mGridCol6-@md which is unwanted from my perspective.

Test case not passing:

t.is(m('mGridCol6@md'), 'mGridCol6@md');

I've came with two solutions:

  1. change the way how camecase is checking case of character
isLastCharLower = c.toLowerCase() === c && c.toUpperCase() !== c;
isLastLastCharUpper = isLastCharUpper;
isLastCharUpper = c.toUpperCase() === c && c.toLowerCase() !== c;
  1. widen the regexp in te final replace: /[_.\- ]+(\w|$)/g insted of /[_.\- ]+(\.|$)/g

But unfortunately that changes the behaviour in the following case:

t.is(m('@M'), '@M');

I'm happy to provide a PR but need suggestion how would you like to deal with it, if ever.

Update README to include browser support

This module is great (just like all your other work!), but I included it in my project without realizing it targeted Node. I know it's my fault for not checking, so I don't blame you at all, but it broke my JS file for an IE11 customer. Would you accept a PR that mentions compatible browsers? If so, I'm happy to work that up.

Add a .npmignore

Hi,
It would be great to add a .npmignore file to this repository so the .editorconfig travis.yml and test.js aren't included in the package when it's used as a dependency.
Ideally it would be something to do in all your repos, but this one is used a lot.
Thanks,
Alvin

Unexpected token: name (isLastCharLower) [./~/camelcase/index.js:4,0]

My dependencies

  "dependencies": {
    "antd": "^2.11.0",
    "antd-mobile": "^1.3.0",
    "babel-plugin-syntax-decorators": "^6.13.0",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-decorators-legacy": "^1.3.4",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
    "babel-preset-stage-1": "^6.24.1",
    "bowser": "^1.7.0",
    "camelcase": "^4.1.0",
    "express": "^4.15.3",
    "fastclick": "^1.0.6",
    "mobx": "^3.1.15",
    "mobx-form-label": "^1.0.8",
    "mobx-form-validate": "^1.0.2",
    "mobx-react": "^4.2.1",
    "moment": "^2.18.1",
    "morgan": "^1.8.2",
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-router": "3.0.2",
    "urijs": "^1.18.10",
    "uuid": "^3.1.0"
  },

My webpack.config.js

        test: /\.(js|jsx)$/,
        include: paths.appSrc,
        loader: require.resolve('babel-loader'),
        options: {
          plugins: [
            ['import', { libraryName: 'antd-mobile', style: true }],
            ['transform-decorators-legacy']
          ],
          presets: ['react', 'es2015', 'stage-0' ],
          cacheDirectory: true,
        }

When I build production code, I got this failed message.

x.trim is not a function (camelcase cannot be used with shorthand)

To reproduce:

// save as `test.js`
const camelCase = require('camelcase');
const keys = [ 'foo', 'bar', 'baz'];
console.log(keys.map(camelCase));
node test
λ ~/Public/mongoose-omit-common-fields/ master* node test
arguments { '0': 'foo', '1': 0, '2': [ 'foo', 'bar', 'baz' ] }
/Users/niftylettuce/Public/test/node_modules/camelcase/index.js:41
      .map(x => x.trim())
                  ^

TypeError: x.trim is not a function
    at Array.from.map.x (/Users/niftylettuce/Public/test/node_modules/camelcase/index.js:41:19)
    at Array.map (<anonymous>)
    at module.exports (/Users/niftylettuce/Public/test/node_modules/camelcase/index.js:41:8)
    at Array.map (<anonymous>)
    at Object.<anonymous> (/Users/niftylettuce/Public/test/test.js:4:18)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)

Subsequent uppercase letters are not converted

Subsequent uppercase letters in a string are not converted to lowercase.

Example:
"XMLHttpRequest" is converted to "xMLHttpRequest" rather than "xmlHttpRequest".

Compared with Lodash

const camelCase = require('camelcase');
const _ = require('lodash');

camelCase('XMLHttpRequest'); // xMLHttpRequest
_.camelCase('XMLHttpRequest'); // xmlHttpRequest

Is this the intended behaviour?

mis-specification

IMO, this lib was mis-specified

the existing results:

camelCase('foo_bar');
//=> 'fooBar' 
 
camelCase('Foo-Bar');
//=> 'fooBar'  

should be this instead:

camelCase('foo_bar');
//=> 'fooBar' 
 
camelCase('Foo-Bar');
//=> 'FooBar'                     // notice uppercase first letter...

but it's too late to change the API as it is - but perhaps you will accept a second argument, like so:

camelCase('Foo-Bar', false);
//=> 'fooBar'  

camelCase('Foo-Bar', true);
//=> 'FooBar'  

camel case names can have an uppercase first letter! :) This seems like a strange oversight, or maybe I am missing something. In other words, PascalCase is a special case of camelCase, they are not exclusive in my mind.

Would you accept a PR for this?

Transpiled dist file missing

It might be addressed by:

  1. add a transpiled version and linked as main in package.json, or
  2. add "presets": [ "es2015" ] in package.json "babel" property

Cannot run tests: update the xo dependency to the latest (currently v0.54.2)

Trying to run the tests it failed every time with the following error

➜ camelcase git:(main) ✗ npm test

[email protected] test
xo && ava && tsd

TypeError: Cannot read properties of undefined (reading 'getAllComments')
Occurred while linting /Users/leomav/camelcase/index.js:1
Rule: "unicorn/expiring-todo-comments"
at Object.Program (/Users/leomav/camelcase/node_modules/eslint/lib/rules/no-warning-comments.js:193:45)
at Program (/Users/leomav/camelcase/node_modules/eslint-plugin-unicorn/rules/expiring-todo-comments.js:511:10)
at /Users/leomav/camelcase/node_modules/eslint-plugin-unicorn/rules/utils/rule.js:39:18
at ruleErrorHandler (/Users/leomav/camelcase/node_modules/eslint/lib/linter/linter.js:1050:28)
at /Users/leomav/camelcase/node_modules/eslint/lib/linter/safe-emitter.js:45:58
at Array.forEach ()
at Object.emit (/Users/leomav/camelcase/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
at NodeEventGenerator.applySelector (/Users/leomav/camelcase/node_modules/eslint/lib/linter/node-event-generator.js:297:26)
at NodeEventGenerator.applySelectors (/Users/leomav/camelcase/node_modules/eslint/lib/linter/node-event-generator.js:326:22)
at NodeEventGenerator.enterNode (/Users/leomav/camelcase/node_modules/eslint/lib/linter/node-event-generator.js:340:14)`

There was an issue in xojs/xo library that was fixed lately eslint/eslint#17167 (comment)
Updating the xo dep to the latest version of this library (currently tried out the v0.54.2) fixes the issue and tests can be ran

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.