Coder Social home page Coder Social logo

mesqueeb / case-anything Goto Github PK

View Code? Open in Web Editor NEW
84.0 2.0 3.0 3.4 MB

camelCase, kebab-case, PascalCase... a simple integration with nano package size. (SMALL footprint!)

Home Page: https://github.com/sponsors/mesqueeb

License: MIT License

JavaScript 1.08% TypeScript 98.92%
change-case case-change change-casing casing-change camel-case camel kebab-case kebab snake-case snake

case-anything's Introduction

Case anything 🐫

Total Downloads Latest Stable Version

npm i case-anything

14 case changing functions: camelCase, kebab-case, PascalCase and more...
A simple integration with nano package size. (SMALL footprint!)

Motivation

I created this package because most other packages that do simple case changing are so big...

Some features I focused on:

  • small footprint (it's 12+ times smaller than the next popular case changing package!!)
  • tree-shakable — only import what you need
  • awesome JSDocs popup documentation on hover
  • fully typed with TypeScript
  • complete coverage with unit testing
  • 0 dependencies
  • Case anything is used in...

  • Famous Mac app Popclip 💊
  • State Management Library Magnetar 🌟
  • Vue Form Generator Blitzar ⚡️
  • Lottie-player ∫
  • OpenAPI CLI Portman 👨🏽‍🚀
  • and 100s more...
  • Usage

    case-anything supports tree-shaking and is side-effect free!

    // just import the functions you need like so:
    import { camelCase, kebabCase } from 'case-anything'

    case-anything has different behaviour if the string you pass has spaces or not.

    • Without spaces it will split and format on every "part" it can detect
    • With spaces it will split and format on every "word" based on those spaces

    Strings without spaces

    Name Input example Output example
    🐪 camelCase camelCase('$catDog') catDog
    🐫 PascalCase
    UpperCamelCase
    pascalCase('$catDog')
    upperCamelCase('$catDog')
    CatDog
    🥙 kebab-case kebabCase('$catDog') cat-dog
    🐍 snake_case snakeCase('$catDog') cat_dog
    📣 CONSTANT_CASE constantCase('$catDog') CAT_DOG
    🚂 Train-Case trainCase('$catDog') Cat-Dog
    🕊 Ada_Case adaCase('$catDog') Cat_Dog
    👔 COBOL-CASE cobolCase('$catDog') CAT-DOG
    📍 Dot.notation dotNotation('$catDog') cat.Dog
    📂 Path/case pathCase('$catDog') $cat/Dog
    🛰 Space case spaceCase('$catDog') $cat Dog
    🏛 Capital Case capitalCase('$catDog') $Cat Dog
    🔡 lower case lowerCase('$catDog') $cat dog
    🔠 UPPER CASE upperCase('$catDog') $CAT DOG

    Special Characters

    You can see that most functions by default remove special characters, and some functions keep special characters.

    functions that remove special characters* functions that keep special characters*
  • camelCase
  • pascalCase
  • kebabCase
  • snakeCase
  • constantCase
  • trainCase
  • adaCase
  • cobolCase
  • dotNotation
  • pathCase
  • spaceCase
  • capitalCase
  • lowerCase
  • upperCase
  • *You can control wether or not to keep or remove special characters like so:

    // default:
    camelCase('$catDog') === 'catDog'
    // force keeping special characters:
    camelCase('$catDog', { keepSpecialCharacters: true }) === '$catDog'
    
    // default:
    pathCase('$catDog') === '$cat/Dog'
    // force removing special characters:
    pathCase('$catDog', { keepSpecialCharacters: false }) === 'cat/Dog'

    Case Changing

    These cases do not change the casing of the words:

    • dotNotation
    • pathCase
    • spaceCase
    // default:
    dotNotation('$catDog') === 'cat.Dog'
    // force lower case:
    dotNotation('$catDog').toLowerCase() === 'cat.dog'

    Strings with spaces

    As soon as there is a space in the target string, it will regard the input as a sentence and only split each part at the spaces.

    Name Input example Output example
    🐪 camelCase camelCase("I'm O.K.!") imOk
    🐫 PascalCase
    UpperCamelCase
    pascalCase("I'm O.K.!")
    upperCamelCase("I'm O.K.!")
    ImOk
    🥙 kebab-case kebabCase("I'm O.K.!") im-ok
    🐍 snake_case snakeCase("I'm O.K.!") im_ok
    📣 CONSTANT_CASE constantCase("I'm O.K.!") IM_OK
    🚂 Train-Case trainCase("I'm O.K.!") Im-Ok
    🕊 Ada_Case adaCase("I'm O.K.!") Im_Ok
    👔 COBOL-CASE cobolCase("I'm O.K.!") IM-OK
    📍 Dot.notation dotNotation("I'm O.K.!") Im.OK
    📂 Path/case pathCase("I'm O.K.!") I'm/O.K.!
    🛰 Space case spaceCase("I'm O.K.!") I'm O.K.!
    🏛 Capital Case capitalCase("I'm O.K.!") I'm O.k.!
    🔡 lower case lowerCase("I'm O.K.!") i'm o.k.!
    🔠 UPPER CASE upperCase("I'm O.K.!") I'M O.K.!

    Also note, that multiple sequential spaces are treated as one space.

    Keep only certain special characters

    Instead of removing all special characters, you can opt to keep some special characters.

    In the example below we see:

    • input: $cat-dog
    • desired output: $CatDog
    pascalCase('$cat-dog', { keepSpecialCharacters: false })
    // CatDog   → not what we want
    
    pascalCase('$cat-dog', { keepSpecialCharacters: true })
    // $Cat-Dog → not what we want
    
    pascalCase('$cat-dog', { keep: ['$'] })
    // $CatDog  → desired output

    Convert special characters into alphabet

    I have extended regular alphabet with the most common Latin-1 Supplement special characters.

    The coolest thing about this library is that it will "convert" special characters into regular alphabet for the cases used as variable names! 😎

    // CONVERTS special characters:
    camelCase('Çâfé Ågård')    === 'cafeAgard'
    pascalCase('Çâfé Ågård')   === 'CafeAgard'
    kebabCase('Çâfé Ågård')    === 'cafe-agard'
    snakeCase('Çâfé Ågård')    === 'cafe_agard'
    constantCase('Çâfé Ågård') === 'CAFE_AGARD'
    trainCase('Çâfé Ågård')    === 'Cafe-Agard'
    adaCase('Çâfé Ågård')      === 'Cafe_Agard'
    cobolCase('Çâfé Ågård')    === 'CAFE-AGARD'
    dotNotation('Çâfé Ågård')  === 'Cafe.Agard'
    
    // DOES NOT convert special characters:
    spaceCase('Çâfé Ågård')    === 'Çâfé Ågård'
    pathCase('Çâfé Ågård')     === 'Çâfé/Ågård'
    lowerCase('Çâfé Ågård')    === 'çâfé ågård'
    upperCase('Çâfé Ågård')    === 'ÇÂFÉ ÅGÅRD'
    capitalCase('Çâfé Ågård')  === 'Çâfé Ågård'

    JSDocs

    I have made sure there is great documentation available on hover!

    jsdocs preview

    Keyboard shortcuts

    With Better Touch Tool you can set up keyboard shortcuts to convert selected text with JavaScript. This repo provides an easy to install preset that has shortcuts for pascal, kebab and camel case! (thanks to @AndrewKoch) It even supports multi-cursors in VSCode!

    Here is an example triggering keyboard shortcuts to convert the selected text to PascalCase; kebab-case; camelCase:

    keyboard shortcuts example

    You can download the BTT preset from the source code: case-anything.bttpreset.

    Package size

    We'll compare this package with blakeembrey/change-case, a very famous package on npm.

    case-anything change-case
    camelCase 1.1K (572) 27.2K (6K)
    pascalCase 1.1K (561) 27.4K (6.1K)
    kebabCase 1.1K (541) 26.8K (5.9K)
    snakeCase 1.1K (540) 26.8K (5.9K)
    constantCase 1.1K (540) 27.2K (6K)
    pathCase 1K (530) 26.8K (5.9K)

    Source code

    What keeps my package small, is that literally just uses a regex to separate "words".

    // the source code is similar to:
    export function splitOnSpecialChars(string: string): any[] {
      return string.match(/^[a-z]+|[A-Z][a-z]+|[a-z]+|[0-9]+|[A-Z]+(?![a-z])/g)
    }

    The actual regex used is a little bit more comprehensive and can be found here.

    Meet the family (more tiny utils with TS support)

    case-anything's People

    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

    Watchers

     avatar  avatar

    case-anything's Issues

    Question: "-" "_" should these be special characters?

    Hi @mesqueeb,

    Sorry to come back to the "special characters" item, when implementating the v2 of case-anything, the special characters results felt a unlogical when it comes to the "-" & "_" characters, that are kept.

    When using for example a PascalCase conversion:

    const valueAsString = "$sample-example-reports"
    
    const result1 = pascalCase(valueAsString,{keepSpecialCharacters: false}) // result = SampleExampleReports
    const result2 = pascalCase(valueAsString,{keepSpecialCharacters: true}) // result = $Sample-Example-Reports

    result1 is logical but for result2 I would have expected: $SampleExampleReports

    My first thought would be that the "-" & "_" would be replace since they are linked to the various casing conversion (kebab-case, snake_case, ...) and the special characters would be all the other characters lik "@", "$", ...

    feat: add train case

    The request "header" keys are typically set as kebab-case but with the first letters as in capital.

    See the Postman screenshot:

    2021-12-28 at 21 37 18@2x

    The normal "kebab-case" transforms the full string to lowercase.
    To facilitate the automatic casing of header keys, it want to get your input if you would be open for a PR to introduce an additional casing: Capital-Kebab-Case?

    /**
     * converts strings to Capital-Kebab-Case
     *
     * @export
     * @param {string} string
     * @returns {string} in Kebab-Case
     */
    function capitalKebabCase(string) {
        return getParts(string, noSpecialChars)
            .map(part => capitaliseWord(part))
            .join('-')
    }

    Example:
    capitalKebabCase('ponytaVaporeonPOLIWRATH_ButterfreeA') => Ponyta-Vaporeon-Poliwrath-Butterfree-A

    Any feedback on the idea is welcome.

    Doesn't support older JS runtimes due to `String.matchAll`

    I tried to update the version of case-anything I'm using in PopClip to 2.x but ran into a small problem. It crashes when I run it on High Sierra (and possibly other older macOS) because the JavaScriptCore runtime on those systems is too old to support String.matchAll(), which is used in the utils module.

    If it were possible to use String.match() instead I think it would work. It's not a showstopper because I can easily carry on using 1.x which actually works really well anyway.

    Node 12/14 - ReplaceAll error

    @mesqueeb

    I noticed that during automated testing using Github actions, after implementation of the case-anything package, that Node 12/14 throws this error:

    (node:2012) UnhandledPromiseRejectionWarning: TypeError: foundPrefix.replaceAll is not a function
            at /home/runner/work/openapi-format/openapi-format/node_modules/case-anything/dist/index.umd.js:54:41
            at Array.map (<anonymous>)
            at splitAndPrefix (/home/runner/work/openapi-format/openapi-format/node_modules/case-anything/dist/index.umd.js:41:36)
            at snakeCase (/home/runner/work/openapi-format/openapi-format/node_modules/case-anything/dist/index.umd.js:158:14)

    Error [ERR_REQUIRE_ESM]: require() of ES Module

    I tried 2.1.3 in my package and I ran into this error:

    } = require("case-anything");
        ^
    
    Error [ERR_REQUIRE_ESM]: require() of ES Module /Users/Sites/asyncapi-format/node_modules/case-anything/dist/index.umd.js from /Users/Sites/asyncapi-format/asyncapi-format.js not supported.
    index.umd.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
    Instead rename index.umd.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /Users/Sites/asyncapi-format/node_modules/case-anything/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
    
        at Object.<anonymous> (/Users/Sites/asyncapi-format/asyncapi-format.js:21:5)
        at Object.<anonymous> (/Users/Sites/asyncapi-format/bin/cli.js:5:24) {
      code: 'ERR_REQUIRE_ESM'

    Version 2.1.2 works without a problem.

    Originally posted by @thim81 in #20 (comment)

    spaceCase doesn't work for snake_case

    It works for camelCase
    For Example

    spaceCase('$catDog') // Output: $cat Dog

    But doesn't for snake_case

    spaceCase('$cat_dog') // Output: $cat_dog 
    // but Expected output: $cat dog

    Weird results when original string consists of all caps

    I'm trying to make some case conversions for certain types of sensors (e.g. pH sensor, TSS sensor etc).

    I haven't covered all the different case types here but I think this is sufficient to indicate there is a fundamental problem with single-letter abbreviated words. For example, in the following code:

    import { capitalCase, kebabCase, camelCase, pascalCase } from 'case-anything';
    
    // From Camel Case
    console.log(pascalCase('tSS'));
    console.log(camelCase('tSS'));
    console.log(capitalCase('tSS'));
    console.log(kebabCase('tSS'));
    
    // From Pascal Case
    console.log(pascalCase('TSS'));
    console.log(camelCase('TSS'));
    console.log(capitalCase('TSS'));
    console.log(kebabCase('TSS'));

    Gives the following wrong results:

    TSs
    tSs
    T Ss
    t-ss
    Tss
    tss
    Tss
    tss
    

    Which is different from the expected result which SHOULD be:

    TSS
    tSS
    T S S
    t-s-s
    TSS
    tSS
    T S S
    t-s-s
    

    By the way the abbreviation "TSS" used here stands for "Total Suspended Solids". I am using "TSS" to shorten strings.

    All that being said, this is a magnificent project and I hope this bug report will help improve it even further. Thanks in advance.

    getParts function will crash if string param is special chars but not match splitOnSpecialChars

    example

    const caseAnything = require('case-anything')
    
    cascaseAnything.camelCase('你好')
    cascaseAnything.kebabCase('こんにちは')

    this code will throw error

    /sandbox/node_modules/case-anything/dist/index.cjs.js:29
        return noSpecialChars ? parts.map(function (part) { return part.normalize('NFD').replace(/[^a-zA-ZØßø0-9]/g, ''); }) : parts;
                                      ^
    
    TypeError: Cannot read property 'map' of null
        at getParts (/sandbox/node_modules/case-anything/dist/index.cjs.js:29:35)
        at Object.camelCase (/sandbox/node_modules/case-anything/dist/index.cjs.js:51:12)
        at Server.<anonymous> (/sandbox/src/index.js:7:28)
        at Server.emit (events.js:198:13)
        at parserOnIncoming (_http_server.js:695:12)
        at HTTPParser.parserOnHeadersComplete (_http_common.js:111:17)

    Erroneous handling of strng 'MSkS'

    Hi,
    I like 'case-anything'. However, I met an edge case today that you should examine.

    The following two conversion differ

    lowerCase('MSkS') // 'm sk s'
    'MSkS'.toLowerCase() // 'msks'
    

    So far, it is the only time I have seen where lowerCase() fails, and I have been using it extensively. I hope you can find out the issue - it did cost be the better part of a day to track the erroneous conversion.

    Sentence case

    Hello, thank you for this wonderful utility library! I was curious if you'd be willing to add a sentenceCase utility? I saw it was briefly considered in #10. I think this would be great for design systems that want to enforce this in UI elements like buttons. Happy to submit a PR if it sounds good 😊

    create a better touch tool case conversion script? [1h]

    I think recent update of "better touch tool" now allows to run JS/node scripts...?

    • Check if that's possible
    • copy paste the dist code for just "camelCase" / "pascalCase" / "kebabCase" into a bettertouchtool JS script.
    • set up 3 keyboard shortcuts that execute those scripts onto selected text.
    • if it's not possible to "execute those scripts onto selected text" try if it's possible to execute it on clipboard text & paste automatically (see shortcut examples below)
    • Check if there is an easy way the shortcuts can be shared to other user's better touch tools.

    I'm thinking a cool shortcut for executing those could be:

    • ⌘⌃C + ⌘⌃P for pascal case ([C]ase [P]ascal)
    • ⌘⌃C + ⌘⌃C for camel case
    • ⌘⌃C + ⌘⌃K for kebab case

    Or if it's easier to implement the scripts that use the "clipboard" information, we can even do this:

    • ⌘C + ⌘⌃P for pascal case ([C]ase [P]ascal)
    • ⌘C + ⌘⌃C for camel case
    • ⌘C + ⌘⌃K for kebab case

    Then the first [C] still stands for [C]ase, but as a side effect we're also putting it onto our clipboards.

    Question: Prevent @ $ characters from being removed

    Hi @mesqueeb,

    Thanks for the creation of such a powerful, yet easy to use package + the footprint is nice & small.

    I noticed that when transforming a string with an @ or $ character, the @ & $ gets removed.
    Example:

    • camelCase("@nextlink") becomes ==> "nextLink"
    • camelCase("$filter") becomes ==> "filter"

    Is there a way to prevent this?

    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.