Coming soon - Get a detailed view of why an account is flagged as spam!
view details

This post has been de-listed

It is no longer included in search results and normal feeds (front page, hot posts, subreddit posts, etc). It remains visible only via the author's post history.

5
Techniques to stop me duplicating logic?
Post Body

I realise this is asking a lot, but does anyone fancy rewriting this js-pseudo-code in typescript as a little exercise ?

I had to contrive a little example, but something i've found myself doing a lot is when i have a type that is 'either this / or that' but logic is same/similar regardless, basically having to copy/paste the logic into multiple branches one for each potential type, so that something like this..

[js pseudocode]

let ptOrSpan = .... some fetch or something
let store = ptOrSpan.type === 'pt' ? ptStore : spanStore
if (store.current === ptOrSpan)
    store.updateCurrent(ptOrSpan)
else 
    store.push(ptOrSpan)

becomes something like..

[typescript pseudocode]

if(ptOrSpan.type === 'pt') {
    if (ptStore.current === ptOrSpan)
        ptStore.updateCurrent(ptOrSpan)
    else 
        ptStore.push(ptOrSpan)
}
if(ptOrSpan.type === 'span') {
    if (spanStore.current === ptOrSpan)
        spanStore.updateCurrent(ptOrSpan)
    else 
        spanStore.push(ptOrSpan)
}

I wondered if there are some typescript features i'm not using that can help cut down on what i see as duplication? Or maybe there's just a better way to structure the code that isn't really anything to do with Typescript?

I'd just be interested to see if anyone could get this to type check without escape hatches and without explicitly having separate branches for Pt and Span. thanks

A playground (these are shareable, right?)

Author
Account Strength
90%
Account Age
8 years
Verified Email
Yes
Verified Flair
No
Total Karma
592
Link Karma
150
Comment Karma
434
Profile updated: 2 days ago
Posts updated: 2 months ago

Subreddit

Post Details

We try to extract some basic information from the post title. This is not always successful or accurate, please use your best judgement and compare these values to the post title and body for confirmation.
Posted
2 years ago