Path to string

Benchmark created on


Setup

const functionalPathToString = path => {
    const matches = path.toString().split("=>");
    const fullStringPath = matches[1]
        .trim().replace(/[()]/g, "");
    const pointIndex = fullStringPath.indexOf(".");
    return pointIndex === -1
        ? ""
        : fullStringPath.substring(pointIndex + 1);
};
    
const resolveAccess = p => p.replace(/\.\[/g, "[");
    
const normalizePart = p => (
    typeof p === "number" 
    || !isNaN(parseFloat(p)) ? `[${p}]` : p
);
    
const pathToStringArray = path => {
    const parts = [];
    const pathProxy = new Proxy({}, {
        get(target, prop) {
            parts.push(prop);
            return pathProxy;
        }
    });
    path(pathProxy);
    return parts;
}
    
const pathToStringNew = path => (
    resolveAccess(pathToStringArray(path).join("."))
);

Test runner

Ready to run.

Testing in
TestOps/sec
pathToStringNew
for (let i = 0; i < 10; ++i) {
    pathToStringArray(p => 
    p.roomCategorySettings[i].seasonalRules[i].name);
}
ready
functionalPathToString
for (let i = 0; i < 10; ++i) {
    functionalPathToString(p => p.roomCategorySettings[0].seasonalRules[1].name);
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.