Skip to content

Instantly share code, notes, and snippets.

@tshemsedinov
Last active December 8, 2021 08:59
Show Gist options
  • Save tshemsedinov/95c25c42577334c2dfd46064098cfec2 to your computer and use it in GitHub Desktop.
Save tshemsedinov/95c25c42577334c2dfd46064098cfec2 to your computer and use it in GitHub Desktop.
Bad code example for students
'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
Copy link

pavelkoshkin92 commented Dec 6, 2021

const pipe = (...fns) => arg => fns.reduce((prev, fn) => fn(prev), arg);
const parsePoint = point => typeof point === 'object' ? point : JSON.parse(point);
const shiftPoint = ({x, y}) => point => ({...point, x: point.x += x, y: point.y += y });
const shiftPoints = (offset, points) => points.map(point => pipe(parsePoint, shiftPoint(offset))(point));

const offset = { x: 10, y: -5 }

const polyline = [
  { x: 0, y: 0 },
  { x: 10, y: 10 },
  '{ "x": 20, "y": 20 }',
  { x: 30, y: 30 }
];

console.log(shiftPoints(offset, polyline));

@OneHedgehog
Copy link

@pavelkoshkin92 this one looks very clean for me 👍

@Kamran92
Copy link

Kamran92 commented Dec 7, 2021

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));

@AntiHero
Copy link

AntiHero commented Dec 7, 2021

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