D
D
devunion2018-03-05 14:15:21
JavaScript
devunion, 2018-03-05 14:15:21

How to write a function in FP style?

I try to use a more functional approach in my work. Unusual, but the pros outweigh the pros. Due to the lack of experience, trivial questions arise. Here is one of them. There is an array of objects of two types: `Word` `Separator`. For example, this: [Word, Separator, Word, Separator, Separator, Word, Separator] or [Word, Separator, Word, Separator, Word] the task is to get the tail of the list to the penultimate word. In the first example it is [Separator, Separator, Word, Separator] in the second it is [Separator, Word] . In procedural style, everything is clear. In functional - too somehow I will write. The question is how to do it beautifully and correctly?
PS. Wrote. But somehow not very...

this.words.reverse().reduce((accum, w) => {
            if (accum.wordsCount == 0) {
                if (w instanceof Word) {
                    accum.wordsCount += 1;
                }
                accum.tail = [w, ...accum.tail];
            } else if (accum.wordsCount == 1) {
                if (w instanceof Separator) {
                    accum.tail = [w, ...accum.tail];
                } else {
                    accum.wordsCount += 1;
                }
            }
            return accum;
        }, {tail: [], wordsCount: 0}).tail;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
ComradV, 2018-03-05
@devunion

In my opinion, the following code is much clearer.
Here, before adding, we look at whether the word is Word, if so, we increase the counter. If it is large (greater than or equal to 2), then do not add, otherwise add. We add to the end, because it works faster. Then we turn around.

this.words.reduceRight((accum, w) => {
    acc.count += (current instanceof Word)?1:0;
    if(acc.count < 2){
      acc.words.push(current);
    }
    return acc;
  }
  , {words:[], count:0}).words.reverse();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question