I Didn't Know You Could Do This in JS

Here’s some sample code:

function isDSTTodayInThisTimeZone(timeZone) {
    // This is the part I didn't know you could do in JS
    // Cache results to avoid recalculating
    if (!isDSTTodayInThisTimeZone.cache) {
        isDSTTodayInThisTimeZone.cache = {};
    }
    if (isDSTTodayInThisTimeZone.cache[timeZone]) {
        return isDSTTodayInThisTimeZone.cache[timeZone];
    }

    const now = new Date();
    const januaryOffset = new Date(now.getFullYear(), 0, 1)
        .toLocaleString("en-US", { timeZone, timeZoneName: "short" })
        .split(" ").pop();
    const julyOffset = new Date(now.getFullYear(), 6, 1)
        .toLocaleString("en-US", { timeZone, timeZoneName: "short" })
        .split(" ").pop();
    const currentOffset = now
        .toLocaleString("en-US", { timeZone, timeZoneName: "short" })
        .split(" ").pop();

    const isDST = currentOffset === Math.min(januaryOffset, julyOffset);
    isDSTTodayInThisTimeZone.cache[timeZone] = isDST;
    return isDST;
}

I didn’t know that you could store a function’s result in a cache belonging to that function. ChatGPT says you can and it seems to work. :slight_smile:

4 Likes

hmm, that’s an interesting way of introduction memoization into a javascript function that Ive not seen before. thanks! This article talks about other ways you can do this and also hints at the complexities of using it in our new (at least in meteor land) async / promise world: Maximizing Performance: How to Memoize Async Functions in JavaScript - DEV Community

1 Like

Thanks for this. I always use closures to memoize function results. Good to know

1 Like

JS is always magic :smiley: :handshake:

2 Likes