1

I have some formatting functions that should be applied on some strings:

const limitSize = (limit: number): ((str: string) => string) => {
  return (str: string) => str.substring(0, limit)
}

const replaceNewLine = (replaceWith: string): ((str: string) => string) => {
  return (str: string) => str.replace(/\n/g, replaceWith)
}

They both return a function that can be applied on a string

How can I chain them together so that the result returns also a function that can be applied on strings?

Is there a lodash utility I'm missing?

2 Answers 2

5

I think you need flow function of Lodash or pipe of Ramda

function square(n) {
  return n * n;
}
 
var addSquare = _.flow([_.add, square]);
addSquare(1, 2);
// => 9
Sign up to request clarification or add additional context in comments.

Comments

1

Just create a new function definition as below:

const limitReplace = (limit: number, replaceWith: string): ((str: string) => string) => {
    return str => replaceNewLine(replaceWith)(limitSize(limit)(str));
}

Used as:

const input = "Hel\nlo W\norld\n";
const limitSixReplaceSpace = limitReplace(6, " ");
const result = limitSixReplaceSpace(input); // Hel lo

2 Comments

I'll probably have more than just these 2 formatting functions so the flow solution is better
Fair enough, you did ask for a lodash solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.