Skip to content

Commit

Permalink
refactor code to be simpler and remove dependency
Browse files Browse the repository at this point in the history
  • Loading branch information
malcolm-kee committed Nov 28, 2018
1 parent a9c2bc7 commit 43661ba
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 18 deletions.
4 changes: 1 addition & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@
"bugs": {
"url": "https://github.com/malcolm-kee/join-string/issues"
},
"dependencies": {
"typesafe-is": "^1.0.1"
},
"dependencies": {},
"devDependencies": {
"@types/jest": "^23.3.9",
"coveralls": "^3.0.2",
Expand Down
24 changes: 15 additions & 9 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
import { isFilledString, isArray, isNumber } from 'typesafe-is';
type JoinFunction = (...items: any[]) => string;

export const joinString = (delimiter: string) =>
function joinFn(...items: Array<any>): string {
export const joinString = (delimiter: string): JoinFunction =>
function joinFn(): string {
const results: Array<string | number> = [];

for (let index = 0; index < items.length; index++) {
const item = items[index];
for (let index = 0; index < arguments.length; index++) {
const item = arguments[index];

if (isNumber(item) || isFilledString(item)) {
if (!item && item !== 0) continue;

const itemType = typeof item;

if (itemType == 'string' || itemType == 'number') {
results.push(item);
continue;
}

if (isArray(item)) {
results.push(joinFn(...item));
continue;
if (Array.isArray(item) && item.length > 0) {
const innerResult = joinFn.apply(null, item);
if (innerResult) {
results.push(innerResult);
}
}
}

Expand Down
4 changes: 3 additions & 1 deletion test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,9 @@ describe('joinString', () => {

test('array will be flatten', () => {
const joinFn = joinString(', ');
expect(joinFn('x', false, undefined, 'y', [false, null, 'z', ''])).toBe('x, y, z');
expect(joinFn('x', false, undefined, [false], 'y', [false, null, 'z', ''])).toBe(
'x, y, z'
);
});
});

Expand Down
5 changes: 0 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3450,11 +3450,6 @@ type-check@~0.3.2:
dependencies:
prelude-ls "~1.1.2"

typesafe-is@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/typesafe-is/-/typesafe-is-1.0.1.tgz#eb86c4276eb27d0e9a99f4c7efd509175a3c2ef0"
integrity sha512-nDxlJeNidbMHAtZg5iWsEJzvLPfiljWxgoRwb0M6uE7FMHD8/blNLclILO3/n7rF8refTSeZ2Pm1e9edf4Detg==

typescript@^3.1.6:
version "3.1.6"
resolved "https://registry.yarnpkg.com/typescript/-/typescript-3.1.6.tgz#b6543a83cfc8c2befb3f4c8fba6896f5b0c9be68"
Expand Down

0 comments on commit 43661ba

Please sign in to comment.