A Tale of Two Functions

Ben Lovy on December 06, 2018

In Which Ben Learns 1 Is The Loneliest Number So, my biggest shortcoming as a developer is my toolkit of algorithms at my fingertips by ... [Read Full]
markdown guide

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)



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


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]
        , ['', '']),

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.


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


I've done the ol' parenthesis match problem with a stack before, and I even remembered that problem when I saw this: "Oh hey, this looks like that one problem I solved with a stack. I should arbitrarily use a linked list here!"

The linked list turned out ok, but I could have saved a couple lines and had a much more coherent solution if I used the stack.

Ah well, c'est la vie.

code of conduct - report abuse