lodash#groupBy TypeScript Examples
The following examples show how to use
lodash#groupBy.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From gant-design with MIT License | 7 votes |
export function getAllChildrenNode(
targetKeys: any[],
api: GridApi,
deleteChildren = false,
): RowNode[] {
const targetNodes: RowNode[] = [];
targetKeys.map(key => {
const itemNode = api.getRowNode(key);
itemNode && targetNodes.push(itemNode);
});
if (deleteChildren) return targetNodes;
const allNodes: RowNode[] = [];
const groupNodes = groupBy(targetNodes, 'level');
let level = min(Object.keys(groupNodes).map(level => level));
while (!isEmpty(groupNodes[level])) {
const list = groupNodes[level];
let nextLevel: any = parseInt(level) + 1;
nextLevel = nextLevel.toString();
groupNodes[nextLevel] = groupNodes[nextLevel] ? groupNodes[nextLevel] : [];
list.map(itemNode => {
const { childrenAfterGroup = [] } = itemNode as RowNode;
groupNodes[nextLevel].push(...childrenAfterGroup);
return itemNode.data;
});
groupNodes[nextLevel] = uniqBy(groupNodes[nextLevel], 'id');
allNodes.push(...list);
level = nextLevel;
}
return allNodes;
}
Example #2
Source File: daily-summary.ts From backstage with Apache License 2.0 | 6 votes |
function countStatusesPerDay(builds: ReadonlyArray<Build>) {
const days = groupBy(builds, value => startOfDay(value.requestedAt));
const foundStatuses = new Set<string>();
const values = Object.entries(days).map(([epoch, buildsThisDay]) => {
const byStatus = countBy(buildsThisDay, 'status');
const value: Epoch & StatusesDatapoint = {
__epoch: parseInt(epoch, 10),
...byStatus,
};
Object.keys(byStatus).forEach(status => {
foundStatuses.add(status);
});
return value;
});
return {
statuses: sortStatuses([...foundStatuses]),
values,
};
}
Example #3
Source File: path.ts From free-swagger with MIT License | 6 votes |
groupByTag = (swagger: OpenAPIV2.Document): ParsedPathsObject =>
groupBy(
// 打平 operationObject 数组
flattenDeep(
Object.entries(swagger.paths).map(
([path, pathItem]: [string, OpenAPIV2.PathItemObject]) =>
Object.entries(pathItem).map(
([method, operationItem]: [Method, OpenAPIV2.OperationObject]) => ({
...operationItem,
method,
url: path,
})
)
)
)
.map((item) => ({
...item,
filename: createFilename(swagger.tags!, item.tags?.[0] ?? ''),
}))
.filter((item) => {
if (!item.tags?.[0]) {
console.log(
chalk.yellow(
`${item.method.toUpperCase()} ${
item.url
} 的 tags 不存在,无法生成该 api`
)
)
return false
}
// TODO 对没有 tags 的 path 做兼容
return !!item.filename
}),
(o) => o.filename
)
Example #4
Source File: GoCdBuildsInsights.tsx From backstage with Apache License 2.0 | 6 votes |
function failureRate(jobs: Job[]): {
title: string;
subtitle: string;
} {
const resultGroups = new Map(
Object.entries(groupBy(jobs, 'result')).map(([key, value]) => [
toBuildResultStatus(key),
value.flat(),
]),
);
const failedJobs = resultGroups.get(GoCdBuildResultStatus.error);
if (!failedJobs) {
return {
title: '0',
subtitle: '(no failed jobs found)',
};
}
resultGroups.delete(GoCdBuildResultStatus.error);
const nonFailedJobs = Array.from(resultGroups.values()).flat();
const totalJobs = failedJobs.length + nonFailedJobs.length;
const percentage = (failedJobs.length / totalJobs) * 100;
const decimalPercentage = (Math.round(percentage * 100) / 100).toFixed(2);
return {
title: `${decimalPercentage}%`,
subtitle: `(${failedJobs.length} out of ${totalJobs} jobs)`,
};
}
Example #5
Source File: assetsDbService.ts From nautilus-wallet with MIT License | 6 votes |
public async sync(assets: IDbAsset[], walletId: number): Promise<void> {
const groups = groupBy(assets, (a) => a.address);
const dbGroups = groupBy(await this.getByWalletId(walletId), (a) => a.address);
const groupKeys = union(keys(dbGroups), keys(groups));
for (const key of groupKeys) {
const group = groups[key];
const dbGroup = dbGroups[key];
if (isEmpty(dbGroup) && isEmpty(groups)) {
continue;
} else if (isEmpty(group) && !isEmpty(dbGroup)) {
await dbContext.assets.bulkDelete(this.primaryKeysFrom(dbGroup));
continue;
} else if (isEmpty(dbGroup)) {
await dbContext.assets.bulkPut(group);
continue;
}
const remove = this.primaryKeysFrom(differenceBy(dbGroup, group, (a) => a.tokenId));
const put = this.newOrChanged(dbGroup, group);
if (remove.length > 0) {
await dbContext.assets.bulkDelete(remove);
}
if (put.length > 0) {
await dbContext.assets.bulkPut(put);
}
}
}
Example #6
Source File: index.tsx From nebula-dashboard with Apache License 2.0 | 6 votes |
updateChart = () => {
const { data } = this.props;
const versionList = groupBy(data, 'version');
const chartData = Object.keys(versionList).map(key => ({
type: key,
value: round(versionList[key].length / data.length, 2),
}));
this.chartInstance.data(chartData).render();
};
Example #7
Source File: ColumnComponent.tsx From next-basics with GNU General Public License v3.0 | 6 votes |
getOptsGroups = (
options: SelectProps["options"],
category: string
): React.ReactNode => {
const optsGroup = Object.entries(groupBy(options, category));
return optsGroup.map(([label, options]) => (
<Select.OptGroup key={label} label={label}>
{getOptions(options)}
</Select.OptGroup>
));
}
Example #8
Source File: ExplicitLoaderImpl.ts From type-graphql-dataloader with MIT License | 6 votes |
constructor(
relation: RelationMetadata,
connection: Connection,
selfKeyFunc: (root: any) => any
) {
super(async (ids) => {
const columns = relation.inverseRelation!.joinColumns;
const k = `${relation.propertyName}_${columns[0].propertyName}`;
const entities = groupBy(
await connection
.createQueryBuilder<V>(relation.type, relation.propertyName)
.where(
`${relation.propertyName}.${columns[0].propertyPath} IN (:...${k})`
)
.setParameter(k, ids)
.getMany(),
selfKeyFunc
);
return ids.map((id) => entities[id] ?? []);
});
}
Example #9
Source File: processor.ts From next-basics with GNU General Public License v3.0 | 6 votes |
export function groupByMoth(
list: ItemProps[] = [],
timeType?: TimeType
): Array<{ groupName: string; list: ItemProps[] }> {
const category = groupBy(list, (item) =>
moment(timeType === "second" ? item.time * 1000 : item.time).format(
"YYYY-MM"
)
);
return Object.entries(category).map(([key, list]) => ({
groupName: key,
list,
}));
}
Example #10
Source File: public.tsx From jetlinks-ui-antd with MIT License | 6 votes |
export function renderUnit(units: any): ReactNode {
const filterOption = (inputValue: string, option: any) => {
return option.key.indexOf(inputValue) != -1;
};
const grouped = groupBy(units, unit => unit.type);
const types = Array.from(new Set<string>(units.map((unit: any) => {
return unit.type;
})));
const options = types.map(type => {
const typeData = grouped[type];
return (
<Select.OptGroup label={type} key={type}>
{
typeData.map((e: Unit) => {
return <Select.Option value={e.id} key={`${e.name}/${e.symbol}`}
title={`${e.name}/${e.symbol}`}>{e.name} / {e.symbol}</Select.Option>
})
}
</Select.OptGroup>
);
});
return (
<AutoComplete
dropdownMatchSelectWidth={false}
dropdownStyle={{width: 300}}
style={{width: '100%'}}
dataSource={options}
optionLabelProp="title"
filterOption={(inputValue, option) => {
return filterOption(inputValue, option);
}}
>
<Input/>
</AutoComplete>
);
}
Example #11
Source File: utils.ts From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
convertDataForGantt = (
data: { expandList: CP_GANTT.IData[]; updateList: CP_GANTT.IData[]; refresh?: boolean },
prevList: CP_GANTT.IGanttData[],
) => {
const { expandList, updateList, refresh } = data;
let ganttData: CP_GANTT.IGanttData[] = refresh ? [] : [...prevList];
const timeConvert = (start: number, end: number) => {
let _start = start && moment(start).startOf('day');
let _end = end && moment(end).endOf('day');
if (!start && end) {
// no start time
_start = moment(_end).startOf('day');
} else if (!end && start) {
_end = moment(_start).endOf('day');
}
return {
start: _start && new Date(_start.valueOf()),
end: _end && new Date(_end.valueOf()),
};
};
const prevDataGroup = { ...groupBy(ganttData, 'pId'), ...expandList };
const convert = (dataTemp: CP_GANTT.IData[], level = 0, pId?: string) => {
dataTemp.forEach((item) => {
const { key, title, start, end, isLeaf = true, hideChildren, ...rest } = item;
const validTime = timeConvert(start, end);
const curData = {
type: !isLeaf ? 'project' : ('task' as CP_GANTT.TaskType),
id: key,
name: title,
start: validTime.start,
end: validTime.end,
progress: 0,
isLeaf,
hideChildren: hideChildren === undefined ? (!isLeaf ? !prevDataGroup[key]?.length : undefined) : hideChildren,
level,
pId: pId || 0,
...(pId ? { project: pId } : {}),
...rest,
};
ganttData.push(curData);
if (prevDataGroup[curData.id]) {
convert(prevDataGroup[curData.id], level + 1, curData.id);
}
});
};
if (expandList) {
ganttData = [];
convert(prevDataGroup['0']); // root: 0
}
if (updateList?.length) {
updateList.forEach((item) => {
const curDataIndex = findIndex(ganttData, (gItem) => gItem.id === item.key);
if (curDataIndex !== -1) {
const { key, title, start, end, isLeaf = true, hideChildren, ...rest } = item;
set(ganttData, `[${curDataIndex}]`, {
...ganttData[curDataIndex],
...rest,
isLeaf,
hideChildren: hideChildren === undefined ? (!isLeaf ? !prevDataGroup[key]?.length : undefined) : hideChildren,
id: key,
name: title,
start: start && new Date(start),
end: end && new Date(end),
type: !isLeaf ? 'project' : 'task',
});
}
});
}
return ganttData;
}
Example #12
Source File: index.tsx From jetlinks-ui-antd with MIT License | 6 votes |
UnitComponent = React.forwardRef((props: UnitProps, ref) => {
const grouped = groupBy(units, unit => unit.typeText);
const types = Array.from(new Set(units.map(unit => unit.typeText)));
function onValueChange(value: any) {
props.onChange && props.onChange(value);
}
return (
<Select onChange={(value: string) => onValueChange(value)} value={props.value}>
{
types.map(type => {
const typeData = grouped[type];
return (
<Select.OptGroup label={type} key={type}>
{
typeData.map((e: Unit) => {
return <Select.Option value={e.id} key={e.id}>{e.name} / {e.symbol}</Select.Option>
})
}
</Select.OptGroup>
);
})
}
</Select>
);
})
Example #13
Source File: commit-detail.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
CommitDetail = () => {
const [commitDetail, sonarMessage] = repoStore.useStore((s) => [s.commitDetail, s.sonarMessage]);
const { getCommitDetail } = repoStore.effects;
const { clearCommitDetail, clearSonarMessage } = repoStore.reducers;
const [isFetching] = useLoading(repoStore, ['getCommitDetail']);
React.useEffect(() => {
getCommitDetail();
return () => {
clearSonarMessage();
clearCommitDetail();
};
}, [clearSonarMessage, getCommitDetail, clearCommitDetail]);
const { commit, diff = {} } = commitDetail;
const fileMap = {};
if (diff && diff.files) {
diff.files.forEach((f: REPOSITORY.IFile) => {
fileMap[f.name] = f;
});
if (sonarMessage.issues) {
const issueGroup = groupBy(sonarMessage.issues, 'path');
map(issueGroup, (issues, path) => {
if (fileMap[path]) {
fileMap[path].issues = issues;
}
});
}
}
return (
<Spin spinning={isFetching}>
<CommitBlock commit={commit} />
<FileDiff diff={diff} disableComment mode="commit" />
</Spin>
);
}
Example #14
Source File: withGroupedOptions.tsx From gio-design with Apache License 2.0 | 6 votes |
getGroupedOptions = (options: any[]) => {
const hasNotGroup = !options.some((option: any) => {
if (option?.groupLabel) {
return true;
}
return false;
});
if (hasNotGroup) {
return options;
}
const groupedOptions = groupBy(options, 'groupLabel');
return Object.keys(groupedOptions).reduce((opts: any[], groupKey: string) => {
const group = get(groupedOptions, `${groupKey}.0.group`);
const groupValue = get(groupedOptions, `${groupKey}.0.groupValue`);
return opts.concat([
{
id: groupValue || groupKey,
value: groupValue || groupKey,
name: groupKey,
label: groupKey,
type: 'groupLabel',
group,
},
...groupedOptions[groupKey],
]);
}, []);
}
Example #15
Source File: traceConvert.ts From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
getRootMostSpan = (traces: MONITOR_TRACE.ITraceSpan[]) => {
const firstWithoutParent = traces.find((s) => !s.parentSpanId);
if (firstWithoutParent) {
return firstWithoutParent;
}
const idToSpanMap = fp.flow(
fp.groupBy((s: MONITOR_TRACE.ITraceSpan) => s.id),
fp.mapValues(([s]) => s),
)(traces);
return recursiveGetRootMostSpan(idToSpanMap, traces[0]);
}
Example #16
Source File: daily-summary.ts From backstage with Apache License 2.0 | 6 votes |
export function dailySummary(builds: ReadonlyArray<Build>): ChartableDaily {
const triggersDaily = countTriggersPerDay(builds);
const statusesDaily = countStatusesPerDay(builds);
const { triggerReasons } = triggersDaily;
const { statuses } = statusesDaily;
const reasonMap = new Map(
triggersDaily.values.map(value => [value.__epoch, value]),
);
const statusMap = new Map(
statusesDaily.values.map(value => [value.__epoch, value]),
);
const days = Object.keys(
groupBy(builds, value => startOfDay(value.requestedAt)),
)
.map(epoch => parseInt(epoch, 10))
.sort();
return {
values: days.map(epoch => ({
__epoch: epoch,
...reasonMap.get(epoch),
...statusMap.get(epoch),
})),
triggerReasons,
statuses,
};
}
Example #17
Source File: Mobility.tsx From wuhan2020-frontend-react-native-app with MIT License | 6 votes |
toSection = (data = []) => {
const grouped = groupBy(data, 't_date');
let rst = [];
Object.keys(grouped).forEach(key => {
rst = rst.concat({
title: key,
data: grouped[key],
});
});
return rst;
}
Example #18
Source File: index.tsx From anew-server with MIT License | 6 votes |
getNoticeData = (notices: API.NoticeIconItem[]): Record<string, API.NoticeIconItem[]> => {
if (!notices || notices.length === 0 || !Array.isArray(notices)) {
return {};
}
const newNotices = notices.map((notice) => {
const newNotice = { ...notice };
if (newNotice.datetime) {
newNotice.datetime = moment(notice.datetime as string).fromNow();
}
if (newNotice.id) {
newNotice.key = newNotice.id;
}
if (newNotice.extra && newNotice.status) {
const color = {
todo: '',
processing: 'blue',
urgent: 'red',
doing: 'gold',
}[newNotice.status];
newNotice.extra = (
<Tag
color={color}
style={{
marginRight: 0,
}}
>
{newNotice.extra}
</Tag>
) as any;
}
return newNotice;
});
return groupBy(newNotices, 'type');
}
Example #19
Source File: github_runner.ts From CIAnalyzer with MIT License | 6 votes |
private setRepoLastRun(repo: GithubConfigRepo, reports: WorkflowReport[]) {
const workflowNameToReports = groupBy(reports, 'workflowName')
for (const [workflowName, reports] of Object.entries(workflowNameToReports)) {
const lastRunReport = maxBy(reports, 'buildNumber')
if (lastRunReport) {
this.store?.setLastRun(`${repo.fullname}-${workflowName}`, lastRunReport.buildNumber)
}
}
}
Example #20
Source File: index.tsx From ant-design-pro-V5-multitab with MIT License | 6 votes |
getNoticeData = (notices: API.NoticeIconData[]): Record<string, API.NoticeIconData[]> => {
if (!notices || notices.length === 0 || !Array.isArray(notices)) {
return {};
}
const newNotices = notices.map((notice) => {
const newNotice = { ...notice };
if (newNotice.datetime) {
newNotice.datetime = moment(notice.datetime as string).fromNow();
}
if (newNotice.id) {
newNotice.key = newNotice.id;
}
if (newNotice.extra && newNotice.status) {
const color = {
todo: '',
processing: 'blue',
urgent: 'red',
doing: 'gold',
}[newNotice.status];
newNotice.extra = (
<Tag
color={color}
style={{
marginRight: 0,
}}
>
{newNotice.extra}
</Tag>
);
}
return newNotice;
});
return groupBy(newNotices, 'type');
}
Example #21
Source File: surveyMedia.ts From aqualink-app with MIT License | 6 votes |
getSurveyPointsByName = (surveyMedia: SurveyMedia[]) => {
const sortedBySurveyPointName = sortBy(
surveyMedia,
(media) => media.surveyPoint?.name
);
const groupedMediaByPointName = groupBy(
sortedBySurveyPointName.map((media) => ({
...media,
surveyPointName: media.surveyPoint?.name || "Other",
})),
"surveyPointName"
);
return Object.entries(groupedMediaByPointName).map(
([name, pointSurveyMedia]) => ({
name,
pointId: pointSurveyMedia[0].surveyPoint?.id,
surveyMedia: pointSurveyMedia,
})
);
}
Example #22
Source File: formatSecurityReport.ts From hub with Apache License 2.0 | 6 votes |
formatSecurityReport = (
vulnerabilities: Vulnerability[] | null
): { list: Vulnerability[]; summary: SecurityReportSummary } => {
const list = vulnerabilities
? orderBy(
vulnerabilities,
[
(vulnerability: Vulnerability) =>
SEVERITY_ORDER.indexOf(vulnerability.Severity.toLowerCase() as VulnerabilitySeverity),
(vulnerability: Vulnerability) => {
const sources = vulnerability.CVSS ? Object.keys(vulnerability.CVSS) : [];
const activeSource =
vulnerability.SeveritySource && sources.includes(vulnerability.SeveritySource)
? vulnerability.SeveritySource
: sources[0];
if (sources.length > 0 && vulnerability.CVSS[activeSource]) {
return vulnerability.CVSS[activeSource].V3Score || vulnerability.CVSS[activeSource].V2Score;
}
},
'PkgName',
],
['asc', 'desc', 'asc']
)
: [];
const sortedBySeverity = groupBy(vulnerabilities, 'Severity');
const summary: SecurityReportSummary = {};
for (let severity in VulnerabilitySeverity) {
const value: VulnerabilitySeverity = severity.toLowerCase() as VulnerabilitySeverity;
if (sortedBySeverity[severity.toUpperCase()]) {
summary[value] = sortedBySeverity[severity.toUpperCase()].length;
} else {
summary[value] = 0;
}
}
return { list: list, summary: summary };
}
Example #23
Source File: daily-summary.ts From backstage with Apache License 2.0 | 6 votes |
function countTriggersPerDay(builds: ReadonlyArray<Build>) {
const days = groupBy(builds, value => startOfDay(value.requestedAt));
const triggerReasons = sortTriggerReasons([
...new Set(
builds
.map(({ triggeredBy }) => triggeredBy)
.filter((v): v is NonNullable<typeof v> => !!v),
),
]);
const values = Object.entries(days).map(([epoch, buildsThisDay]) => {
const datapoint = Object.fromEntries(
triggerReasons
.map(reason => [
reason,
buildsThisDay.filter(build => build.triggeredBy === reason).length,
])
.filter(([_type, count]) => count > 0),
) as Omit<TriggerReasonsDatapoint, '__epoch'>;
// Assign the count for this day to the first value this day
const value: Epoch & TriggerReasonsDatapoint = Object.assign(datapoint, {
__epoch: parseInt(epoch, 10),
});
return value;
});
return { triggerReasons, values };
}
Example #24
Source File: turn.ts From fishbowl with MIT License | 6 votes |
export function drawableCards(
turns: CurrentGameSubscription["games"][0]["turns"],
cards: CurrentGameSubscription["games"][0]["cards"]
) {
const allCompletedCardIds = flatMap(turns, (turn) => turn.completed_card_ids)
const maxCount = max(values(countBy(allCompletedCardIds)))
let completedCardIdsForRound = filter(
groupBy(allCompletedCardIds),
(arr) => arr.length === maxCount
).map((arr) => arr[0])
const remainingIdsForRound = difference(
cards.map((card) => card.id),
completedCardIdsForRound
)
if (remainingIdsForRound.length === 0) {
return cards
} else {
return filter(cards, (card) => remainingIdsForRound.includes(card.id))
}
}
Example #25
Source File: graph.ts From nebula-studio with Apache License 2.0 | 6 votes |
getExploreInfo = async (payload) => {
const { data, expand } = payload;
const { vertexes, edges } = data;
const _vertexes = await this.getExploreVertex({
ids: vertexes,
expand,
});
let _edges: any = groupBy(edges, (e) => e.edgeType);
_edges = await Promise.all(
Object.values(_edges).map(async (item) => {
return this.getExploreEdge(item);
})
);
if (this.nodes.size === 0 && _vertexes.length !== 1) {
// make round position width init data
makeRoundPosition(_vertexes, { x: 0, y: 0 });
}
this.addNodesAndEdges({
vertexes: _vertexes,
edges: _edges.flat(),
});
};
Example #26
Source File: count-builds-per-day.ts From backstage with Apache License 2.0 | 6 votes |
export function countBuildsPerDay(
values: ReadonlyArray<ChartableStageDatapoints>,
) {
const days = groupBy(values, value => startOfDay(value.__epoch));
Object.entries(days).forEach(([_startOfDay, valuesThisDay]) => {
const counts = Object.fromEntries(
statusTypes
.map(
type =>
[
type,
valuesThisDay.filter(value => value[type] !== undefined).length,
] as const,
)
.filter(([_type, count]) => count > 0)
.map(([type, count]): [Countify<FilterStatusType>, number] => [
`${type} count`,
count,
]),
);
// Assign the count for this day to the first value this day
Object.assign(valuesThisDay[0], counts);
});
}
Example #27
Source File: app-type-select.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
render() {
const { imgOptions, value, onChangeType } = this.props;
const optionGroup = groupBy(imgOptions, 'groupIndex');
return (
<div className="app-type-select">
{map(optionGroup, (options, key) => {
return (
<div key={key} className="app-type-group">
{options.map((img) => {
const { disabled, disabledTip } = img;
const cls = classnames('img-wrapper', {
active: value === img.value && !disabled,
'disabled-card': disabled,
});
return (
<Tooltip key={img.value} title={disabled ? disabledTip : null}>
<div
className={cls}
onClick={() => {
if (!disabled) {
onChangeType(img.value);
}
}}
>
<img src={img.src} alt={img.name || 'image-option'} />
<CustomIcon type="yuanxingxuanzhongfill" />
<Tooltip title={img.name}>
<div className="desc truncate">{img.name}</div>
</Tooltip>
</div>
</Tooltip>
);
})}
</div>
);
})}
</div>
);
}
Example #28
Source File: circleci_client.ts From CIAnalyzer with MIT License | 5 votes |
// https://circleci.com/api/v1.1/project/:vcs-type/:username/:project?circle-token=:token&limit=20&offset=5&filter=completed
async fetchWorkflowRuns(owner: string, repo: string, vcsType: string, lastRunId?: number) {
const limit = (this.options.debug) ? DEBUG_PER_PAGE : 100
let recentBuilds = [] as RecentBuildResponse[]
for (let index = 0; index < FETCH_RECENT_BUILD_API_NUM; index++) {
const res = await this.axios.get( `project/${vcsType}/${owner}/${repo}`, {
params: {
// API default is 30 and max is 100
// ref: https://circleci.com/docs/api/#recent-builds-for-a-single-project
limit: limit,
// limit: 3,
offset: index * limit,
// filter: "completed"
shallow: true,
}
})
recentBuilds.push(...res.data)
}
recentBuilds = (lastRunId)
? recentBuilds.filter((build) => build.build_num > lastRunId)
: recentBuilds
// Add dummy workflow data if job is not belong to workflow
for (const build of recentBuilds) {
if (!build.workflows) {
build.workflows = this.createDefaultWorkflow(build)
}
}
const groupedBuilds = groupBy(recentBuilds.map((build) => {
return {
workflow_name: build.workflows.workflow_name,
workflow_id: build.workflows.workflow_id,
reponame: build.reponame,
username: build.username,
vcs_type: vcsType,
build_num: build.build_num,
lifecycle: build.lifecycle,
}
}), 'workflow_id')
const workflowRuns: WorkflowRun[] = Object.values(groupedBuilds).map((builds) => {
const build = builds[0]
const build_nums = builds.map((build) => build.build_num)
return {
workflow_id: build.workflow_id,
workflow_name: build.workflow_name,
reponame: build.reponame,
username: build.username,
vcs_type: build.vcs_type,
build_nums,
lifecycles: builds.map((build) => build.lifecycle),
last_build_num: max(build_nums)!,
}
})
return this.filterWorkflowRuns(workflowRuns)
}
Example #29
Source File: buildTVLList.ts From rewarder-list with GNU Affero General Public License v3.0 | 5 votes |
buildTVLList = async (network: Network): Promise<void> => {
const dir = `${__dirname}/../../data/${network}/`;
await fs.mkdir(dir, { recursive: true });
const rewarderMetas = JSON.parse(
(await fs.readFile(`${dir}/all-rewarders.json`)).toString()
) as Record<string, RewarderMeta>;
const quarriesByStakedMint = mapValues(
groupBy(
Object.values(rewarderMetas).flatMap((rew) =>
rew.quarries.map((q) => ({
address: q.stakedToken.mint,
quarry: q.quarry,
}))
),
(q) => q.address
),
(v) => v.map((q) => q.quarry)
);
const tokenList = JSON.parse(
(await fs.readFile(`${dir}/token-list.json`)).toString()
) as TokenList;
const coingeckoIDs = Object.keys(quarriesByStakedMint).reduce(
(acc: Record<string, string>, mint) => {
const id = tokenList.tokens.find((t) => t.address === mint)?.extensions
?.coingeckoId;
if (id) {
acc[mint] = id;
}
return acc;
},
{}
);
const tvl = { quarriesByStakedMint, coingeckoIDs };
await fs.writeFile(`${dir}/tvl.json`, stringify(tvl));
}