Skip to content Skip to sidebar Skip to footer

Most Elegant Way To Parse,scale And Re-string A String Of Number Co-ordinates

Let's assume we have this string var coords='10,10 20,20 30,30 20,10 60,80' Let's further assume each of the above are XY co-ordinates. Now I'd like to 'scale each item by a factor

Solution 1:

You could split with space and comma and apply the factor to each number and join later.

functionscaleCoords(string, left, right) {
    var f = [left, right];
    return string.split(' ').map(function (a) {
        return a.split(',').map(function (b, i) {
            return b * f[i];
        });
    }).join(' ');
}

var coords = "10,10 20,20 30,30 20,10 60,80";
console.log(scaleCoords(coords, 0.5, 2)); // '5,20 10,40 15,60 10,20 30,160'

ES6 with rest parameters ...

functionscaleCoords(s, ...f) {
    return s.split(' ').map(a => a.split(',').map((b, i) => b * f[i])).join(' ');
}

var coords = "10,10 20,20 30,30 20,10 60,80";
console.log(scaleCoords(coords, 0.5, 2)); // '5,20 10,40 15,60 10,20 30,160'

Solution 2:

Or a slight modification to avoid the extra overhead of calling map and join for the coordinate pair

var data = "10,10 20,20 30,30 20,10 60,80";
functionscaleNumString(s,xs,ys){
    return s.split(" ").map(c=>((x,y)=>x*xs+","+y*ys)(...c.split(","))).join(" ");
}
scaleNumString(data,0.5,0.5)

Or

return s.split(" ").map(c=>(a=>a[0]*xs+","+a[1]*ys)(c.split(","))).join(" ");

Or

return s.replace(/[0-9]+,[0-9]+/g,a=>(a=>a[0]*xs+","+a[1]*ys)(a.split(",")));

Post a Comment for "Most Elegant Way To Parse,scale And Re-string A String Of Number Co-ordinates"