-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoordinate-transformation.js
More file actions
72 lines (68 loc) · 2.4 KB
/
Copy pathcoordinate-transformation.js
File metadata and controls
72 lines (68 loc) · 2.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// @ts-check
//
// The line above enables type checking for this file. Various IDEs interpret
// the @ts-check directive. It will give you helpful autocompletion when
// implementing this exercise.
/**
* Create a function which returns a function making use of a closure to
* perform a repeatable 2d translation of a coordinate pair.
*
* @param {number} dx the translate x component
* @param {number} dy the translate y component
*
* @returns {function} a function which takes an x, y parameter, returns the
* translated coordinate pair in the form [x, y]
*/
export function translate2d(dx, dy) {
return (/** @type {number} */ x, /** @type {number} */ y) => {
return [x + dx, y + dy];
};
}
/**
* Create a function which returns a function making use of a closure to
* perform a repeatable 2d scale of a coordinate pair.
*
* @param {number} sx the amount to scale the x component
* @param {number} sy the amount to scale the y component
*
* @returns {function} a function which takes an x, y parameter, returns the
* scaled coordinate pair in the form [x, y]
*/
export function scale2d(sx, sy) {
return (/** @type {number} */ x, /** @type {number} */ y) => {
return [x * sx, y * sy];
};
}
/**
* Create a composition function which returns a function that combines two
* functions to perform a repeatable transformation
*
* @param {function} f the first function to apply
* @param {function} g the second function to apply
*
* @returns {function} a function which takes an x, y parameter, returns the
* transformed coordinate pair in the form [x, y]
*/
export function composeTransform(f, g) {
return (/** @type {any} */ x, /** @type {any} */ y) => {
let [xCoordinate, yCoordinate] = f(x, y);
return g(xCoordinate, yCoordinate);
};
}
/**
* Return a function which memoizes the last result. If the arguments are the same as the last call,
* then memoized result returned.
*
* @param {function} f the transformation function to memoize, assumes takes two arguments 'x' and 'y'
*
* @returns {function} a function which takes and x, y argument, and will either return the saved result
* if the arguments are the same on subsequent calls, or compute a new result if they are different.
*/
export function memoizeTransform(f) {
let cache = {};
return (/** @type {any} */ x, /** @type {any} */ y) => {
if (cache[[x, y]]) return cache[[x, y]];
cache[[x, y]] = f(x, y);
return cache[[x, y]];
};
}