bltcrew
bltcrew

Reputation: 166

Transform a string to another string using lodash

In order to work in a functional programming way, I want to transform a string without having to use a temporary variable. I would like to do that only using pure JS or lodash.

Given (as asked by @nina-scholz):

const input = 'a string from somewhere';
const option1 = true;
const option2 = false;
const applyOption1 = str => 'prefix-' + str;
const applyOption2 = str => str + '-suffix';
const myFilter = str => str.contains('somewhere');

What I have:

let cleanedInput = input;
if (option1) {
  cleanedInput = applyOption1(cleanedInput);
}
if (option2) {
  cleanedInput = applyOption2(cleanedInput);
}

return _.chain(cleanedInput)
  .split('')
  .filter(blabla)
  .value();

What I want:

return _.chain(input)
  .SOMETHING(value => (option1 ? applyOption1(value) : value))
  .SOMETHING(value => (option2 ? applyOption2(value) : value))
  .split('')
  .filter(blabla)
  .value();

I would foolishly use map but it iterates over chars of the string. So what can I use for SOMETHING ?

Thanks!

Upvotes: 2

Views: 533

Answers (1)

bltcrew
bltcrew

Reputation: 166

Thanks to @gruff-bunny, the method I was searching for is thru

Another solution I found was to put my string in an array, then do a head() after all my map calls.

Upvotes: 2

Related Questions