Last active
November 27, 2018 11:24
-
-
Save taxigy/298d7edaa9d2b03083292ff547e4ff32 to your computer and use it in GitHub Desktop.
A minuscule reusable lib in JS to begin working with collections
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
const mult = (...args) => args.reduce((t, c) => t * c); | |
const array = (size, value) => new Array(size).fill(value); | |
const zeros = size => array(size, 0); | |
const partition = (size, coll) => { | |
if (size === undefined && coll === undefined) { | |
return partition; | |
} | |
if (coll === undefined) { | |
return coll2 => partition(size, coll2); | |
} | |
if (size <= 0) { | |
return coll; | |
} | |
const result = []; | |
const length = coll.length; | |
for (let i = 0; i < length; i += size) { | |
result.push(coll.slice(i, i + size)); | |
} | |
return result; | |
}; | |
const split = (size, coll) => { | |
const items = coll.length / size; | |
const result = []; | |
for (let i = 0; i < coll.length; i += items) { | |
result.push(coll.slice(i, i + items)); | |
} | |
return result; | |
}; | |
const reshape = (dims, coll) => { | |
if (dims === undefined && coll === undefined) { | |
throw new Error("z"); | |
} | |
if (coll.length !== mult(...dims)) { | |
throw new Error("z"); | |
} | |
if (coll === undefined) { | |
return coll2 => reshape(dims, coll2); | |
} | |
if (dims.length <= 1) { | |
return coll; | |
} | |
const [first, ...rest] = dims; | |
return split(first, coll).map(c => reshape(rest, c)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment