blob: c1ae6a7addc6bff4f868b249cedc2e637826f029 [file] [log] [blame]
/********************************************************************************
* Copyright (c) 2020 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
********************************************************************************/
import {Pipe, PipeTransform} from "@angular/core";
@Pipe({
name: "pair"
})
export class PairPipe implements PipeTransform {
/**
* Transforms an array to an array of pair elements. For example, [0, 1, 2, 3] is transformed to [[0, 1], [2, 3]].
* @param array Array to transform
* @param pairSize Maximal size of each pair (default = 2)
*/
public transform<T>(array: T[], pairSize: number = 2): T[][] {
if (!Array.isArray(array)) {
return [];
}
pairSize = Math.max(Math.round(pairSize), 1);
const result: T[][] = [];
for (let i = 0; i < array.length; i += pairSize) {
const pair = Array(pairSize)
.fill(0).map((_, index) => array[i + index])
.filter((item) => item != null);
if (pair.length > 0) {
result.push(pair);
}
}
return result;
}
}