Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
sindresorhus committed May 5, 2024
0 parents commit 142b38b
Show file tree
Hide file tree
Showing 11 changed files with 198 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
root = true

[*]
indent_style = tab
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.yml]
indent_style = space
indent_size = 2
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto eol=lf
21 changes: 21 additions & 0 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: CI
on:
- push
- pull_request
jobs:
test:
name: Node.js ${{ matrix.node-version }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node-version:
- 22
- 18
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node-version }}
- run: npm install
- run: npm test
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
yarn.lock
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
23 changes: 23 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
Convert a string to a valid [JavaScript identifier](https://developer.mozilla.org/en-US/docs/Glossary/Identifier).
Different inputs will always generate unique identifiers.
@example
```
import toValidIdentifier from 'to-valid-identifier';
toValidIdentifier('foo');
//=> 'foo'
toValidIdentifier('foo-bar');
//=> 'foo$j$bar'
toValidIdentifier('$');
//=> '$a$'
toValidIdentifier('undefined');
//=> '$_undefined$'
```
*/
export default function toValidIdentifier(value: string): value is string;
17 changes: 17 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import reservedIdentifiers_ from 'reserved-identifiers';
import base62 from '@sindresorhus/base62';

const reservedIdentifiers = reservedIdentifiers_({includeGlobalProperties: true});

export default function toValidIdentifier(value) {
if (typeof value !== 'string') {
throw new TypeError(`Expected a string, got \`${typeof value}\`.`);
}

if (reservedIdentifiers.has(value)) {
// We prefix with underscore to avoid any potential conflicts with the Base62 encoded string.
return `$_${value}$`;
}

return value.replaceAll(/\P{ID_Continue}/gu, x => `$${base62.encodeInteger(x.codePointAt(0))}$`);
}
9 changes: 9 additions & 0 deletions license
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
MIT License

Copyright (c) Sindre Sorhus <[email protected]> (https://sindresorhus.com)

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
52 changes: 52 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"name": "to-valid-identifier",
"version": "0.0.0",
"description": "Convert a string to a valid JavaScript identifier",
"license": "MIT",
"repository": "sindresorhus/to-valid-identifier",
"funding": "https://github.com/sponsors/sindresorhus",
"author": {
"name": "Sindre Sorhus",
"email": "[email protected]",
"url": "https://sindresorhus.com"
},
"type": "module",
"exports": {
"types": "./index.d.ts",
"default": "./index.js"
},
"sideEffects": false,
"engines": {
"node": ">=18"
},
"scripts": {
"test": "xo && ava"
},
"files": [
"index.js",
"index.d.ts"
],
"keywords": [
"valid",
"identifier",
"safe",
"sanitize",
"variable",
"property",
"ecmascript",
"javascript",
"js",
"reserved",
"keyword",
"word",
"property"
],
"dependencies": {
"@sindresorhus/base62": "^0.1.0",
"reserved-identifiers": "^1.0.0"
},
"devDependencies": {
"ava": "^6.1.2",
"xo": "^0.58.0"
}
}
47 changes: 47 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# to-valid-identifier

> Convert a string to a valid [JavaScript identifier](https://developer.mozilla.org/en-US/docs/Glossary/Identifier)
## Install

```sh
npm install to-valid-identifier
```

## Usage

```js
import toValidIdentifier from 'to-valid-identifier';

toValidIdentifier('foo');
//=> 'foo'

toValidIdentifier('foo-bar');
//=> 'foo$j$bar'

toValidIdentifier('$');
//=> '$a$'

toValidIdentifier('undefined');
//=> '$_undefined$'
```

## API

### toValidIdentifier(string)

Convert the given string to a valid JavaScript identifier.

Different inputs will always generate unique identifiers.

## Use cases

- **Code Generation:** Automate safe variable naming in scripts, avoiding syntax errors from invalid characters.
- **Compilers/Transpilers:** Essential for non-JavaScript languages compiling to JavaScript, ensuring that identifiers are compliant.
- **Dynamic Function Names:** Generate unique and valid function names from dynamic content such as user inputs or database fields.
- **API Wrappers:** Convert API response properties into valid JavaScript object keys for easier access.
- **Template Processing:** Ensure template placeholders are converted to valid JavaScript identifiers when replaced with dynamic values.

## Related

- [is-identifier](https://github.com/sindresorhus/is-identifier) - Check if a string is a valid JavaScript identifier
13 changes: 13 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import test from 'ava';
import toValidIdentifier from './index.js';

test('main', t => {
t.is(toValidIdentifier('foo'), 'foo');
t.is(toValidIdentifier('$foo'), '$a$foo');
t.is(toValidIdentifier('foo-bar'), 'foo$j$bar');
t.is(toValidIdentifier('null'), '$_null$');
t.is(toValidIdentifier('undefined'), '$_undefined$');
t.is(toValidIdentifier('$'), '$a$');
t.is(toValidIdentifier(''), '');
t.is(toValidIdentifier('🦄'), '$XfI$');
});

0 comments on commit 142b38b

Please sign in to comment.