Skip to content

Instantly share code, notes, and snippets.

@joshwcomeau
Last active October 6, 2017 15:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshwcomeau/a8e7e72d2d8029d56f682dda6c602083 to your computer and use it in GitHub Desktop.
Save joshwcomeau/a8e7e72d2d8029d56f682dda6c602083 to your computer and use it in GitHub Desktop.
Snail
const compose = (a, b) => x => a(b(x));
const reverse = array => [...array].reverse();
// `get` is a simple accessor function, used for selecting an item in an array.
const get = id => array => array[id];
// This functional version of map accepts our function first.
const map = (fn, array) => array.map(fn);
// `pluck` allows us to map through a matrix, gathering all the items at a
// specific index.
const pluck = (index, data) => map(get(index), data);
// `rangeFrom` creates an array equal in length to the array provided,
// but with a 0-based range for values.
// eg. ['a', 'b', 'c'] -> [0, 1, 2]
const rangeFrom = ({length}) => [...Array(length).keys()];
const flipMatrix = matrix => (
map(index => pluck(index, matrix), rangeFrom(matrix))
);
const rotateMatrix = compose(flipMatrix, reverse);
const flipMatrixCounterClockwise = compose(reverse, rotateMatrix);
const rotateMatrixCounterClockwise = compose(reverse, flipMatrix);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment