re: A Tale of Two Functions VIEW POST

VIEW FULL DISCUSSION
 

Haha, yes! Thankfully at least this one was cake for me, but only because I've spent the better part of this year continuously writing tuple-based reductions for work >. <

import { from } from 'rxjs'
import { reduce, map } from 'rxjs/internal/operators'

type StringPair = [string, string];

const isUpperCase = (char: string) => !(char.charCodeAt(0) & 0x20);
const isLowerCase = (char: string) => !isUpperCase(char);
const isReactabletype = ([left, right]: StringPair) =>
    left.toLowerCase() === right.toLowerCase();

const isReactivePair = ([left, right]: StringPair) =>
    isReactabletype([left, right])
    && ((isUpperCase(left) && isLowerCase(right))
        || (isUpperCase(right) && isLowerCase(left)));

const printReactivePairs = (str: string) => from(str.split('')).pipe(
    reduce(([previous, result]: StringPair, val: string) =>
        isReactivePair([previous, val]) ?
            [result.charAt(result.length - 2), result.slice(0, result.length - 1)]
            : [val, result + val]
        , <StringPair>['', '']),
    map(([_, result]) => result)
).subscribe(console.log);

printReactivePairs('dabAcCaCBAcCcaDA');

 

Nice and concise! rxjs looks great, I should give it a look.

 

It's definitely nice if you have to do js. Since you're already using F#, elmish is probably the best option overall :) They can also be mixed at runtime.

github.com/elmish/elmish

All signs keep pointing here. Guess I gotta go :)

 

Was thinking, the most concise version of this just exploits the ascii table to eliminate most of the checks. And also probably fails code review:

     reduce(([previous, result], val: string) =>
        previous !== result &&
            (Math.abs(previous.charCodeAt(0) - val.charCodeAt(0))) === 0x20
            ? [result.charAt(result.length - 2), result.slice(0, result.length - 1)]
            : [val, result + val]
        , ['', '']),
code of conduct - report abuse