From ba9656059ba14887202463d02a6bca9edb3203a4 Mon Sep 17 00:00:00 2001 From: Spencer Brower Date: Thu, 15 Jun 2023 13:40:26 -0400 Subject: [PATCH] fix: beforeFirst now returns the input when needle is not present. --- src/index.spec.ts | 4 ++-- src/index.ts | 10 +++++++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/index.spec.ts b/src/index.spec.ts index 4d1fc13..3486515 100644 --- a/src/index.spec.ts +++ b/src/index.spec.ts @@ -71,8 +71,8 @@ describe("strings", () => { expect(beforeFirst(" ", "foo bar bat")).toBe("foo"); }); - it("removes everythin when needle is not present", () => { - expect(beforeFirst("&", "foo bar bat")).toBe(""); + it("returns the input when needle is not present", () => { + expect(beforeFirst("&", "foo bar bat")).toBe("foo bar bat"); }); }); // describe('afterFirstWord', () => { diff --git a/src/index.ts b/src/index.ts index 4c19d56..0096591 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,9 +23,13 @@ export const afterLast = curry((separator: string, str: string) => str.substring(str.lastIndexOf(separator) + 1, str.length) ); -export const beforeFirst = curry((separator: string, str: string) => - str.substring(0, str.indexOf(separator)) -); +export const beforeFirst = curry((separator: string, str: string) => { + const index = str.indexOf(separator); + + return index === -1 + ? str + : str.substring(0, index) +}); // @todo Test export const beforeFirstWord = beforeFirst(" ");