tamino-martinius / node-ts-dedent

TypeScript package which smartly trims and strips indentation from multi-line strings
MIT License
159 stars 8 forks source link

Dedenting doesn't work when using on stored strings #2

Closed karrtikr closed 3 years ago

karrtikr commented 4 years ago

I had my string stored in a variable, and used dedent on it.

        const string = `
        Leading and trailing lines will be trimmed, so you can write something like
        this and have it work as you expect:

          * how convenient it is
          * that I can use an indented list
              - and still have it do the right thing

        That's all.
      `;
        const dedentedString1 = dedent`
        Leading and trailing lines will be trimmed, so you can write something like
        this and have it work as you expect:

          * how convenient it is
          * that I can use an indented list
              - and still have it do the right thing

        That's all.
      `;
        const dedentedString2 = dedent`
      ${string}
    `;

dedentedString2 did not dedent the string at all.

        Leading and trailing lines will be trimmed, so you can write something like
        this and have it work as you expect:

          * how convenient it is
          * that I can use an indented list
              - and still have it do the right thing

        That's all.

Not sure if this is a feature request or a bug.

tamino-martinius commented 4 years ago

Thanks for the report - the actual behavior is intentional as dedent is just removing extra whitespace added by code not the ones by variables

    const originalValue = `
      Leading and trailing lines will be trimmed, so you can write something like
      this and have it work as you expect:

        * how convenient it is
        * that I can use an indented list
            - and still have it do the right thing

      That's all.
    `;
    const dedentedValue = dedent`
      Leading and trailing lines will be trimmed, so you can write something like
      this and have it work as you expect:

        * how convenient it is
        * that I can use an indented list
            - and still have it do the right thing

      That's all.
    `;
    expect(dedentedValue).toEqual(dedent(originalValue));
    expect(dedentedValue).not.toEqual(dedent`
      ${originalValue}
    `);
    expect(dedentedValue).toEqual(dedent`
      ${dedent(originalValue)}
    `);

Anyways i may add a deepDedent which also dedents passed values as this should be pretty easy.

In the meantime just wrap the variable with an extra dedent function call and it should work

So instead of

const dedentedString2 = dedent`
  ${string}
`;

use

const dedentedString2 = dedent`
  ${dedent(string)}
`;
karrtikr commented 4 years ago

the actual behavior is intentional

I thought so. Thanks for the workaround. Btw, even simply using

const dedentedString2 = dedent(`\n${string}`)

instead worked for me.