Last active
December 8, 2021 08:59
-
-
Save tshemsedinov/95c25c42577334c2dfd46064098cfec2 to your computer and use it in GitHub Desktop.
Bad code example for students
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
let movePoints = (offset, points) => { | |
points.forEach((point) => { | |
const type = typeof point; | |
if (type === 'object') { | |
point.x += offset.x; | |
point.y += offset.y; | |
} else { | |
let i = points.indexOf(point); | |
points[i] = JSON.parse(point); | |
points[i].x += offset.x; | |
points[i].y += offset.y; | |
} | |
}); | |
return points; | |
}; | |
const polyline = [ | |
{ x: 0, y: 0 }, | |
{ x: 10, y: 10 }, | |
'{ "x": 20, "y": 20 }', | |
{ x: 30, y: 30 }, | |
]; | |
movePoints({ x: 10, y: -5 }, polyline); | |
console.log({ polyline }); |
pavelkoshkin92
commented
Dec 6, 2021
•
@pavelkoshkin92 this one looks very clean for me 👍
const movePoints = (offset, points) => {
return points
.map((point) => (typeof point === 'string' ? JSON.parse(point) : point))
.map(({ x, y }) => ({
x: x + offset.x,
y: y + offset.y,
}));
};
const polyline = [
{ x: 0, y: 0 },
{ x: 10, y: 10 },
'{ "x": 20, "y": 20 }',
{ x: 30, y: 30 },
];
console.log(movePoints({ x: 10, y: -5 }, polyline));
const validatePoint = (p) => typeof p === "string" ? JSON.parse(p) : p;
const movePoint = (p, { x, y }) => ({...p, x: p.x + x, y: p.y + y,});
const movePoints = (o, ps) => ps.map((p) => movePoint(validatePoint(p), o));
const polyline = [
{ x: 0, y: 0 },
{ x: 10, y: 10 },
'{ "x": 20, "y": 20 }',
{ x: 30, y: 30 },
];
console.log(movePoints({ x: 10, y: -5 }, polyline));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment