Skip to content

Instantly share code, notes, and snippets.

@yuriuliam
Last active April 2, 2022 19:32
Show Gist options
  • Save yuriuliam/97e7c007cd18c44f82168f1c7bb58313 to your computer and use it in GitHub Desktop.
Save yuriuliam/97e7c007cd18c44f82168f1c7bb58313 to your computer and use it in GitHub Desktop.
[TS/JS] Array split functions. One to split based on it's size, the other based on a given predicate.
/**
*
* @param {Array<T>} array The array to be sorted.
* @param {number} size The size of the array.
* @returns {Array<Array<T>>} The sorted array.
* @template {T} T The type of the array.
*/
function splitArrayBySize<T>(array: Array<T>, size: number): Array<Array<T>> {
if (!Array.isArray(array)) {
throw new TypeError(`Expected an array, received ${typeof array}`)
}
if (size <= 0) {
throw new RangeError(`Expected a positive number, received ${size}`)
}
const result = []
for (let i = 0; i < array.length; i += size) {
result.push(array.slice(i, i + size))
}
return result
}
/**
*
* @param {Array<T>} array The array to be sorted.
* @param {(element: T, index: number, array: Array<T>) => boolean} predicate The predicate to be used. It receives the current element, the index of the element and the current array. It should return true if the element should be included in the first result, otherwise false.
* @returns {[Array<T>, Array<T>]} A tuple type with 2 arrays. The first array contains the elements which returned true to the predicate. The second array contains the elements which returned false to the predicate.
* @template {T} T The type of the array.
*/
function splitArray<T>(array: Array<T>, predicate: (element: T, index: number) => boolean): [Array<T>, Array<T>] {
if (!Array.isArray(array)) {
throw new TypeError(`Expected an array, received ${typeof array}`)
}
if (typeof predicate !== 'function') {
throw new TypeError(`Expected a function, received ${typeof predicate}`)
}
const result: [Array<T>, Array<T>] = [[], []]
for (let i = 0; i < array.length; i++) {
const element = array[i]
const shouldInclude = predicate(element, i)
if (shouldInclude) {
result[0].push(element)
} else {
result[1].push(element)
}
}
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment