Question

I have a string that contains coordinates and some whitesace:

E.G. "SM10,10 50,50 20,10\nFM10,20 30,40"

I'd like to extract the list of coordinates:

["10,10", "50,50", "20,10", "10,20", "30,40"]

And then perform some transform (let's say scale by 5) and produce a resultant string:

"SM50,50 250,250 100,50\nFM50,100 140,200"

What's the most performant way to perform this transformation in JavaScript?

Was it helpful?

Solution

Update:

This should be exactly what you needed. It finds and makes the changes to the coordinates in the string and reassembles the string in the format that it started. Let me know if you think its missing something.

function adjust(input) {
    var final = "";
    var lastIndex;
    var temp = [];
    var regex;

    var coords = input.match(/\d+,\d+/g);

    if (coords) {
        for (i = 0; i < coords.length; i++) {
            temp = coords[i].split(",");

            temp[0] *= 5;
            temp[1] *= 5;

            regex = new RegExp("([^0-9])?" + coords[i] + "([^0-9])?","g");
            regex.exec(input);

            lastIndex = parseInt(regex.lastIndex);

            final += input.slice(0, lastIndex).replace(regex, "$1" + temp.join(",") + "$2");
            input = input.slice(lastIndex, input.length);

            temp.length = 0;
        }
    }

    return final + input;
}


Previous answer:

Here, fast and effective:

var coords = "SM10,10 50,50 20,10\nFM10,20 30,40".match(/\d{1,2},\d{1,2}/g);
for (i = 0; i < coords.length; i++) {
    var temp = coords[i].split(",");
    temp[0] *= 5;
    temp[1] *= 5;
    coords[i] = temp.join(",");
}

alert (coords.join(","));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top