Skip to content

Commit

Permalink
feat: add package.json parser #20
Browse files Browse the repository at this point in the history
  • Loading branch information
regevbr committed Apr 23, 2020
1 parent 7e6d3c1 commit f4c70a5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
33 changes: 27 additions & 6 deletions src/utils/predicateBuilder/stringSplitter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import splitter = require('split-string');

const regexMatcher = /^\/(.+)\/([igmsuy]*)$/i;
const regexMatcher = /^\/(.+)\/(i)?$/i;

const regexParser = (input: string): string | RegExp => {
const match = regexMatcher.exec(input);
Expand All @@ -10,29 +10,50 @@ const regexParser = (input: string): string | RegExp => {
return new RegExp(match[1], match[2]);
};

const quotes = [`/`];
const quotes = [`"`, `'`, `\``];
const splitterDefaults = {
quotes,
brackets: {
' /': `/`,
',/': `/`,
'/': `/`,
},
};

const spaceSplitter = (str: string): string[] => {
// @ts-ignore
return splitter(str, {
separator: ` `,
quotes,
...splitterDefaults,
});
};

const commaSplitter = (str: string): string[] => {
// @ts-ignore
return splitter(str, {
separator: `,`,
quotes,
...splitterDefaults,
});
};

const trimmer = (str: string): string => str.trim();
const quouteStip = () => {
let stripped = false;
return (str: string, quote: string): string => {
if (!stripped && str.startsWith(quote) && str.endsWith(quote)) {
stripped = true;
return str.substr(1, str.length - 2);
}
return str;
};
};

const trimmer = (str: string): string => {
return quotes.reduce(quouteStip(), str);
};

export const split = (str: string | undefined): (string | RegExp)[] => {
if (!str) {
return [];
}
return commaSplitter(str).flatMap(spaceSplitter).map(trimmer).filter(Boolean).map(regexParser);
return commaSplitter(` ${str}`).flatMap(spaceSplitter).map(trimmer).filter(Boolean).map(regexParser);
};
9 changes: 5 additions & 4 deletions test/src/utils/predicateBuilder/stringSplitter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe(`string splitter`, () => {
});

it(`should split by space`, () => {
expect(split(`a b c d`)).toEqual([`a`, `b`, `c`, `d`]);
expect(split(`a "b " c d 'f g' \`',f\``)).toEqual([`a`, `b `, `c`, `d`, `f g`, `',f`]);
});

it(`should split by comma`, () => {
Expand All @@ -29,6 +29,10 @@ describe(`string splitter`, () => {
expect(split(`a/sdf/f`)).toEqual([`a/sdf/f`]);
});

it(`should parse regex with / in it`, () => {
expect(split(`/sd\\/f/`)).toEqual([/sd\/f/]);
});

it(`should not confuse regex with wrong flags`, () => {
expect(split(`/s/pm`)).toEqual([`/s/pm`]);
});
Expand All @@ -45,7 +49,4 @@ describe(`string splitter`, () => {
expect(split(`/a/i`)).toEqual([/a/i]);
});

it(`should handle based on regex global flag`, () => {
expect(split(`/a/g`)).toEqual([/a/g]);
});
});

0 comments on commit f4c70a5

Please sign in to comment.