so I'm struggling to understand this code. Can someone please explain how does function move works? Like I watched a lecture about it, but I still don't understand it.
const parse = (point) => {
return typeof point === "object" ? point : JSON.parse(point);
};
const move = (offset) => (point) =>{
point.x += offset.x;
point.y += offset.y;
return point
};
const polyline = [
{ x: 0, y: 0 },
{ x: 10, y: 10 },
'{ "x": 20, "y": 20 }',
{ x: 30, y: 30 },
];
const offset = move({ x: 10, y: -5 });
const path = polyline.map(parse).map(offset);
console.log({ path });
Here's how it was done previously, and this code is an optimised version of that code:
const shift = (offset, points) => {
let modifiedPoints = [];
points.forEach((point) => {
point = parse(point);
point.x += offset.x;
point.y += offset.y;
modifiedPoints.push(point);
});
return modifiedPoints;
};
It is called currying
The passed created function will in your case add 10 to x and subtract 5 from y from each of the polylines in the array
If you call it with
move({ x: 5, y: -15 }); it will offset each line by 5,-15
const parse = (point) => {
return typeof point === "object" ? point : JSON.parse(point); // did we get an object or a string? if the latter parse it
};
// move takes an offset and returns a function that uses that offset (closure)
const move = (offset) => (point) =>{
point.x += offset.x;
point.y += offset.y;
return point
};
// an array of objects or valid JSON strings
const polyline = [
{ x: 0, y: 0 },
{ x: 10, y: 10 },
'{ "x": 20, "y": 20 }', // this will be parsed
{ x: 30, y: 30 },
];
const offset = move({ x: 10, y: -5 }); // offset is returning a function to be used in the map
const path = polyline.map(parse).map(offset); // call the function for each parsed entry in the polyline
console.log({ path });