How to compare a legacy javascript method implementation with a new one?

50 Views Asked by At

I would like to have some easy way to support me while rewriting legacy functions/methods.

Say we have a legacy function and a rewritten one:

var legacyFunction = function() { return 1; };
var reloadedFunction = function() { return 1; };

Is it possible to compare legacyFunction and reloadedFunction side-by-side, in the context where they are executed in production?

I have in mind something along those lines:

return rewriteLegacyCode((usagePerDevice, steps) => {
    // broken implementation
   for (let i = 0; i < inclusiveVolumeSteps.length; i++) {
       if (usage >= steps[i].volume && usage < steps[i + 1].volume) {
           return inclusiveVolumeSteps[i];      
       }
    }
    return undefined;
}).withNewVersion((usagePerDevice, steps) => {
    return steps.findLast((step) => step.volume <= usagePerDevice});
})
.compareResults(usagePerDevice, inclusiveVolume)
.trustNewVersion();

I am looking for a nice implementation

1

There are 1 best solutions below

0
On

I myself wrote the following code -- so far only dealing with non-async stuff:

    class RewriteHelper {
        #legacyVersion;
        #rewriteVersion;
        #results;

        legacyVersion(callback) {
            this.#legacyVersion = callback;
            return this;
        }

        withNewVersion(callback) {
            this.#rewriteVersion = callback;
            return this;
        }

        invokeAndLogException(version, callback, ...args) {
            console.debug(`*** ${version} version ***`);
            try {
                return callback(...args);
            } catch (e) {
                console.warn(`Error: ${e}`)
                return undefined
            }
        }

        compareResults(...args) {
            // with catch for the case the invoked function throws an exception

            let result1 = this.invokeAndLogException('legacy', this.#legacyVersion, ...args);
            let result2 = this.invokeAndLogException('rewritten', this.#rewriteVersion, ...args);

            let result1Json = JSON.stringify(result1, 2);
            let result2Json = JSON.stringify(result2, 2);

            console.log(`Comparing legacy implementation with rewritten one:\nold: ${result1Json}\nnew: ${result2Json}\nresult: ${result1Json === result2Json ? "OK ✅" : "ERROR ❌"}`);
            this.#results = [result1, result2];
            return this;
        }

        trustLegacyVersion() {
            return this.#results[0]
        }

        trustNewVersion() {
            return this.#results[1]
        }

    }

    const rewriteLegacyCode = (callback) => {
        return new RewriteHelper().legacyVersion(callback);
    }