lodash#filter TypeScript Examples
The following examples show how to use
lodash#filter.
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: dcs_util.ts From project-tauntaun with GNU Lesser General Public License v3.0 | 7 votes |
export function getStaticUnit(dcsStaticData: DcsStaticData, groupCategory: string, unit: Unit) {
switch (groupCategory) {
case 'vehicle_group': {
return filter(dcsStaticData.vehicles, vehicle => vehicle.id === unit.type).pop();
}
case 'ship_group': {
return dcsStaticData.ships[unit.type];
}
default:
return undefined;
}
}
Example #2
Source File: addon.utils.ts From WowUp with GNU General Public License v3.0 | 7 votes |
export function getAddonDependencies(
addon: Addon,
dependencyType: AddonDependencyType | undefined = undefined
): AddonDependency[] {
if (dependencyType === undefined) {
return addon.dependencies ?? [];
}
return filter(addon.dependencies, (dep) => dep.type === dependencyType);
}
Example #3
Source File: util.ts From S2 with MIT License | 7 votes |
generateSwitchResult = (state: SwitcherState): SwitcherResult => {
const generateFieldResult = (items: SwitcherItem[]): SwitcherResultItem => {
const flattenValues = (list: SwitcherItem[]) =>
flatten(
map(list, ({ children, ...rest }) => {
return [{ ...rest }, ...flattenValues(children)];
}),
);
const allItems = flattenValues(items);
// get all hidden values
const hideItems = filter(
allItems,
(item: SwitcherItem) => item.checked === false,
);
return {
items: allItems,
hideItems,
};
};
return {
[FieldType.Rows]: generateFieldResult(state[FieldType.Rows]),
[FieldType.Cols]: generateFieldResult(state[FieldType.Cols]),
[FieldType.Values]: generateFieldResult(state[FieldType.Values]),
};
}
Example #4
Source File: utils.ts From aqualink-app with MIT License | 7 votes |
filterHistoricalMonthlyMeanData = (
historicalMonthlyMean: HistoricalMonthlyMeanData[],
from?: string,
to?: string
) => {
if (!from || !to) {
return historicalMonthlyMean;
}
const start = moment(from);
const end = moment(to);
const closestToStart = getHistoricalMonthlyMeanDataClosestToDate(
historicalMonthlyMean,
new Date(start.toISOString())
)?.value;
const closestToEnd = getHistoricalMonthlyMeanDataClosestToDate(
historicalMonthlyMean,
new Date(end.toISOString())
)?.value;
const closestToStartArray: HistoricalMonthlyMeanData[] = closestToStart
? [{ date: start.toISOString(), value: closestToStart }]
: [];
const closestToEndArray: HistoricalMonthlyMeanData[] = closestToEnd
? [{ date: end.toISOString(), value: closestToEnd }]
: [];
const filteredData = historicalMonthlyMean.filter((item) =>
inRange(moment(item.date).valueOf(), start.valueOf(), end.valueOf() + 1)
);
return [...closestToStartArray, ...filteredData, ...closestToEndArray];
}
Example #5
Source File: utils.tsx From erda-ui with GNU Affero General Public License v3.0 | 7 votes |
getTableList = (data: IPerm, scope: string, filterKey: string) => {
let list = [] as any[];
const countData = (curData: any, key = scope, depth = 0, prevData = {}) => {
if (!curData) return;
if (curData.role) {
list.push({ ...prevData, action: { ...curData, key } });
} else {
const { name, ...rest } = curData;
map(rest, (item, cKey) => {
const curPrevData = { ...prevData, [`depth${depth}`]: { key, name } };
countData(item, cKey, depth + 1, curPrevData);
});
}
};
countData(data);
if (filterKey) {
list = filter(list, (l) => some(l, (item) => item.key.includes(filterKey) || item.name.includes(filterKey)));
}
const maxDeepthObj = maxBy(list, (item) => Object.keys(item).length);
const tableList = [] as any[];
map(list, (item) => {
const itemData = { ...item };
map(maxDeepthObj, (val, key) => {
if (!itemData[key]) {
itemData[key] = {};
}
});
const sortKeys = sortBy(Object.keys(itemData), (k) => (k.startsWith('depth') ? Number(k.slice(5)) : 1000));
itemData.actionKey = map(sortKeys, (k) => itemData[k].key || '__').join('');
tableList.push(itemData);
});
return map(
sortBy(tableList, (item) => item.actionKey),
({ actionKey, ...rest }) => rest,
);
}
Example #6
Source File: optimize.ts From sc2-planner with MIT License | 6 votes |
export function setConstraintList(list: Constraint[]): string {
const constraintList = filter(
list.map((constraint: Constraint) => {
if (constraint.type === "order") {
return `${constraint.name}#${constraint.pos + 1}<=${constraint.followingName}#${
constraint.followingPos + 1
}`
}
const afterStr =
constraint.after === -Infinity
? ""
: `${CONVERT_SECONDS_TO_TIME_STRING(constraint.after)}<=`
const beforeStr =
constraint.before === Infinity
? ""
: `<=${CONVERT_SECONDS_TO_TIME_STRING(constraint.before)}`
const nameStr = afterStr || beforeStr ? `${constraint.name}#${constraint.pos + 1}` : ""
return `${afterStr}${nameStr}${beforeStr}`
})
)
return constraintList.join("\n")
}
Example #7
Source File: manifest-handling.ts From ui5-language-assistant with Apache License 2.0 | 6 votes |
export function getFlexEnabledFlagForXMLFile(xmlPath: string): boolean {
const manifestFilesForCurrentFolder = filter(
Object.keys(manifestData),
(manifestPath) => xmlPath.startsWith(dirname(manifestPath))
);
const closestManifestPath = maxBy(
manifestFilesForCurrentFolder,
(manifestPath) => manifestPath.length
);
if (closestManifestPath === undefined) {
return false;
}
return manifestData[closestManifestPath].flexEnabled;
}
Example #8
Source File: dcs_util.ts From project-tauntaun with GNU Lesser General Public License v3.0 | 6 votes |
export function getGroupsWithClients(mission: Mission) {
return wu(getGroups(mission))
.filter(g => g.group.units.find(u => !isSkillAI(u.skill)) !== undefined)
.toArray();
}
Example #9
Source File: addon.utils.ts From WowUp with GNU General Public License v3.0 | 6 votes |
export function getProviders(addon: Addon): AddonExternalId[] {
return filter(getAllProviders(addon), (extId) => extId.providerName !== addon.providerName);
}
Example #10
Source File: pivot-data-set.ts From S2 with MIT License | 6 votes |
public getTotalStatus = (query: DataType) => {
const { columns, rows } = this.fields;
const isTotals = (dimensions: string[], isSubTotal?: boolean) => {
if (isSubTotal) {
const firstDimension = find(dimensions, (item) => !has(query, item));
return firstDimension && firstDimension !== first(dimensions);
}
return every(dimensions, (item) => !has(query, item));
};
const getDimensions = (dimensions: string[], hasExtra: boolean) => {
return hasExtra
? dimensions.filter((item) => item !== EXTRA_FIELD)
: dimensions;
};
return {
isRowTotal: isTotals(
getDimensions(rows, !this.spreadsheet.isValueInCols()),
),
isRowSubTotal: isTotals(rows, true),
isColTotal: isTotals(
getDimensions(columns, this.spreadsheet.isValueInCols()),
),
isColSubTotal: isTotals(columns, true),
};
};
Example #11
Source File: utils.ts From aqualink-app with MIT License | 6 votes |
getSurveyDates = (surveys: SurveyListItem[]): number[] =>
surveys
.filter(({ diveDate }) => !isNil(diveDate))
.map(({ diveDate }) => new Date(diveDate as string).setHours(0, 0, 0, 0))
Example #12
Source File: score.ts From fishbowl with MIT License | 6 votes |
export function teamScore(
team: Team,
turns: CurrentGameSubscription["games"][0]["turns"],
players: CurrentGameSubscription["games"][0]["players"]
) {
const teamPlayerIds = filter(players, (player) => player.team === team).map(
(player) => player.id
)
const teamTurns = filter(turns, (turn) =>
teamPlayerIds.includes(turn.player_id)
)
return flatMap(teamTurns, (turn) => turn.completed_card_ids).length
}
Example #13
Source File: index.tsx From next-basics with GNU General Public License v3.0 | 6 votes |
// 对前端搜索数据进行表头筛选项过滤
private handleFrontendFilters(
dataSource: Record<string, any>[]
): Record<string, any>[] {
let tempDataSource: Record<string, any>[] = dataSource || [];
const filtersArray = map(this.filters, (item, k) => ({
key: k,
value: item,
})).filter((item) => !isNil(item.value) && item.value.length !== 0);
tempDataSource = tempDataSource.filter((item) => {
return every(filtersArray, (filter) => {
return filter.value?.includes(get(item, filter.key)) ?? true;
});
});
return tempDataSource;
}
Example #14
Source File: profile.repository.ts From linkedin-private-api with MIT License | 6 votes |
getProfilesFromResponse = <T extends { included: (LinkedInMiniProfile | { $type: string })[] }>(
response: T,
): Record<ProfileId, MiniProfile> => {
const miniProfiles = filter(response.included, p => p.$type === MINI_PROFILE_TYPE) as LinkedInMiniProfile[];
const transformedMiniProfiles = miniProfiles.map((miniProfile: LinkedInMiniProfile) => transformMiniProfile(miniProfile));
return keyBy(transformedMiniProfiles, 'profileId');
}
Example #15
Source File: go-to.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
pathFormat = (url: string) => (params: object) => {
const necessaryArg: string[] = [];
const [_path, _query] = url.split('?');
// query不算必须的路由参数
const newPath = _path.replace(/\{(\w+)\}/g, (_, key) => {
necessaryArg.push(key);
return params[key];
});
const lostArg = filter(necessaryArg, (arg: string) => params[arg] === undefined);
if (lostArg.length) {
// eslint-disable-next-line no-console
console.error('Jump missing parameters:', lostArg, `in url: ${url}`);
return undefined;
}
if (!_query) {
return newPath;
}
let newQuery = _query.replace(/\{(\w+)\}/g, (_, key) => {
return params[key] !== undefined && params[key] !== null ? params[key] : '';
});
// 移除空的query参数
newQuery = qs.stringify(pickBy(qs.parse(newQuery), (v: any) => v !== ''));
return newQuery ? [newPath, newQuery].join('?') : newPath;
}
Example #16
Source File: InjectRandomIds.ts From gio-design with Apache License 2.0 | 6 votes |
/**
* 解决 SVG 组件 ID 重复问题的高阶组件
* @param Component 需要传入的 SVG 组件
* @returns 注入随机 ID 后的 SVG 组件
*/
export default function InjectRandomIds<P>(
Component: ComponentType<P>
): ComponentType<P & RefAttributes<SVGSVGElement>> {
return function WrapperComponent(props) {
const componentRef = useRef<SVGSVGElement>();
useLayoutEffect(() => {
if (!componentRef.current) return;
const elementsWithId = componentRef.current.querySelectorAll('svg [id]');
const elementsWithFill = componentRef.current.querySelectorAll('svg [fill^=url\\(\\#]');
elementsWithId.forEach((element) => {
const id = element.getAttribute('id');
const elementsWithFillSameId = filter(elementsWithFill, (item) => item.getAttribute('fill') === `url(#${id})`);
elementsWithFillSameId.forEach((node) => {
if (node) {
const newId = `${id}__${uniqueId()}`;
element.setAttribute('id', newId);
node.setAttribute('fill', `url(#${newId})`);
}
});
});
}, []);
return React.createElement(Component, { ...props, ref: componentRef });
};
}
Example #17
Source File: mySql-builder.service.ts From EDA with GNU Affero General Public License v3.0 | 6 votes |
public processFilter(filter: any, columnType: string) {
filter = filter.map(elem => {
if (elem === null || elem === undefined) return 'ihatenulos';
else return elem;
});
if (!Array.isArray(filter)) {
switch (columnType) {
case 'text': return `'${filter}'`;
//case 'text': return `'${filter}'`;
case 'numeric': return filter;
case 'date': return `STR_TO_DATE('${filter}','%Y-%m-%d')`
}
} else {
let str = '';
filter.forEach(value => {
const tail = columnType === 'date'
? `STR_TO_DATE('${value}','%Y-%m-%d')`
: columnType === 'numeric' ? value : `'${value.replace(/'/g, "''")}'`;
str = str + tail + ','
});
return str.substring(0, str.length - 1);
}
}
Example #18
Source File: list.monad.ts From relate with GNU General Public License v3.0 | 6 votes |
/**
* Remove all null, undefined, None, or Nil values (shallow)
* ```ts
* const listOfEmpties = List.from([[], 'foo', null, None])
* const compacted = listOfEmpties.compact()
* compacted.toArray() // [[], 'foo']
* ```
*/
compact<R extends Exclude<T, null | undefined | None<any> | Nil>>(): List<R> {
// @ts-ignore
return this.filter((val) => {
return val !== null && val !== undefined && !Nil.isNil(val) && !None.isNone(val);
});
}
Example #19
Source File: classifierSearch.ts From condo with MIT License | 6 votes |
public async findRulesByIds (query: ITicketClassifierRuleWhereInput, type: string, selectedIds: string[]): Promise<ITicketClassifierRuleUIState[]> {
const filtered = []
for (const key in query)
filtered.push(...this.rules.filter(rule => query[key].ids.includes(rule[key].id)))
if (filtered.length === 0)
return this.rules
for (const selectedId of selectedIds) {
if (!filtered.find(rule => rule[type].id === selectedId)) {
filtered.push(...this.rules.filter(rule => rule[type].id === selectedId))
}
}
return filtered
}
Example #20
Source File: competition.service.ts From wise-old-man with MIT License | 6 votes |
function getTeamCSV(details: CompetitionDetails, teamName: string): string {
const columns = [
{ header: 'Rank', value: (_, index) => index + 1 },
{ header: 'Username', value: row => row.displayName },
{ header: 'Start', value: row => row.progress.start },
{ header: 'End', value: row => row.progress.end },
{ header: 'Gained', value: row => row.progress.gained },
{ header: 'Last Updated', value: row => formatDate(row.updatedAt) }
];
const headers = columns.map(c => c.header).join(',');
const rows = details.participants
.filter(p => p.teamName === teamName)
.map((p, i) => columns.map(c => c.value(p, i)).join(','));
return [headers, ...rows].join('\n');
}
Example #21
Source File: Optimize.tsx From sc2-planner with MIT License | 5 votes |
render(): JSX.Element {
const classes = CLASSES.dropDown
const classesDropdown = this.state.show ? `visible ${classes}` : `hidden ${classes}`
if (this.state.show) {
setTimeout(() => this.componentDidMount())
}
const optionlessSettings = filter(
this.props.optimizeSettings,
(setting: ISettingsElement) =>
!/Option[0-9]+/.test(`${setting.variableName}`) &&
(setting.races === undefined || `${setting.races}`.indexOf(this.props.race) >= 0)
)
const doesHaveConstraints = getConstraintList(optionlessSettings).length > 0
const settingsElements = optionlessSettings.map((item, index) => {
const addiItems = filter(this.props.optimizeSettings, (setting) =>
new RegExp(`^${item.variableName}Option[0-9]+$`).test(`${setting.variableName}`)
)
const additionalField = addiItems.map((item) =>
this.createInput(item, doesHaveConstraints)
)
const classes = [
CLASSES.dropDownContainer,
"flex flex-col",
index > 0 ? "border-t border-black pt-3" : "",
]
const applyButton: JSX.Element | undefined = item.apply ? (
<div
className={`${CLASSES.dropDownButton} m-2 p-2`}
onClick={(e) => this.onApply(e, item.variableName)}
onMouseEnter={(e) => this.mouseEnterFunc(e, item.tooltip)}
data-tip
data-for="optimizeSettingsTooltip"
>
{item.apply}
</div>
) : undefined
return (
<div key={index} className={classes.join(" ")}>
{this.createInput(item, doesHaveConstraints)}
{additionalField}
{applyButton}
</div>
)
})
// TODO Add apply button because onChange doesnt work reliably (laggy behavior)
const settingsButton = (
<div
className={CLASSES.buttons}
onMouseEnter={this.showSettings}
onMouseLeave={this.hideSettings}
>
Optimize
<div className={classesDropdown}>{settingsElements}</div>
</div>
)
return (
<div>
<ReactTooltip place="bottom" id="optimizeSettingsTooltip" className="max-w-xs">
{this.state.tooltipText}
</ReactTooltip>
{settingsButton}
</div>
)
}
Example #22
Source File: namespace.ts From ui5-language-assistant with Apache License 2.0 | 5 votes |
/**
* Suggests Namespaces inside Element
* For example xmlns:m should provide list of namespaces ending with .m.. (like "sap.m", "sap.ui.core.mvc")
* attribute is namespace attribute if it's equal to "xmlns" or starts with "xmlns:"
* in first case all possible namespaces of semantic module will be provided excluding pre-existing ones
*/
export function namespaceKeysSuggestions(
opts: UI5AttributeNameCompletionOptions
): UI5NamespacesInXMLAttributeKeyCompletion[] {
const ui5Model = opts.context;
const xmlElement = opts.element;
if (opts.prefix === undefined) {
return [];
}
const xmlnsPrefix = getXMLNamespaceKeyPrefix(opts.prefix);
if (xmlnsPrefix === undefined) {
return [];
}
const existingNamespacesAttributes: XMLAttribute[] = filter(
xmlElement.attributes,
isExistingNamespaceAttribute
);
const existingNamespacesNames = compact(
map(existingNamespacesAttributes, (_) => _.value)
);
const applicableNamespaces = filter(ui5Model.namespaces, (_) =>
isNamespaceApplicable(_, xmlnsPrefix)
);
const suggestedNamespaces = reject(applicableNamespaces, (_) =>
includes(existingNamespacesNames, ui5NodeToFQN(_))
);
return map(suggestedNamespaces, (_) => ({
type: "UI5NamespacesInXMLAttributeKey",
ui5Node: _,
astNode: opts.attribute as XMLAttribute,
}));
}
Example #23
Source File: issue-1014-spec.ts From S2 with MIT License | 5 votes |
describe('Formatter Tests', () => {
let s2: SpreadSheet;
beforeEach(() => {
s2 = new PivotSheet(getContainer(), dataCfg, s2options);
s2.render();
});
test('corner should not be formatted', () => {
const cornerNodes = filter(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
s2.facet.getCornerHeader().getChildren(),
(node) => node instanceof CornerCell,
) as unknown[] as CornerCell[];
const provinceCornerNode = cornerNodes.find(
(cell) => get(cell, 'meta.field') === 'province',
);
const cityCornerNode = cornerNodes.find(
(cell) => get(cell, 'meta.field') === 'city',
);
expect(get(provinceCornerNode, 'meta.value')).toStrictEqual('省份');
expect(get(provinceCornerNode, 'meta.label')).toStrictEqual('省份');
expect(get(cityCornerNode, 'meta.value')).toStrictEqual('城市');
expect(get(cityCornerNode, 'meta.label')).toStrictEqual('城市');
});
test('row should not be formatted', () => {
const rowNodes = s2.getRowNodes();
const provinceRowNode = rowNodes.find(({ field }) => field === 'province');
expect(provinceRowNode.label).toStrictEqual('浙江');
expect(provinceRowNode.value).toStrictEqual('浙江');
});
test('column should not be formatted', () => {
const colNodes = s2.getColumnNodes();
const cityColNode = colNodes.find(({ field }) => field === 'city');
expect(cityColNode.label).toStrictEqual('义乌');
expect(cityColNode.value).toStrictEqual('义乌');
});
test('data cell should render formatted value', () => {
const priceDataCells = s2.interaction.getPanelGroupAllDataCells();
expect(priceDataCells).not.toHaveLength(0);
expect(priceDataCells).toSatisfyAll(
(cell) => cell.getActualText() === 'price:1',
);
});
});
Example #24
Source File: utils.ts From aqualink-app with MIT License | 5 votes |
createDatasets = (
datasets: ChartProps["datasets"],
surveys: ChartProps["surveys"],
selectedSurveyDate?: Date
): ChartDataSets[] => {
const surveyDates = getSurveyDates(surveys || []);
const processedDatasets = datasets
?.filter(({ displayData }) => displayData)
?.map(
({
label,
data,
type,
fillColor,
curveColor,
threshold,
fillColorAboveThreshold,
fillColorBelowThreshold,
maxHoursGap,
}) => {
const processedData = data
.filter(({ value }) => !isNil(value))
.map(({ value, timestamp }) => ({
x: timestamp,
y: value,
}));
const chartData =
typeof maxHoursGap === "number"
? createGaps(processedData, maxHoursGap)
: processedData;
return {
type,
label,
fill:
!!fillColor ||
!!fillColorAboveThreshold ||
!!fillColorBelowThreshold,
borderColor: curveColor,
borderWidth: 2,
pointRadius: 0,
cubicInterpolationMode:
"monotone" as ChartDataSets["cubicInterpolationMode"],
backgroundColor:
isNumber(threshold) &&
fillColorAboveThreshold &&
fillColorBelowThreshold
? chartFillColor(
threshold,
fillColorAboveThreshold,
fillColorBelowThreshold
)
: fillColor,
data: chartData,
};
}
);
const datasetToAttachSurveysOn = datasets?.find(
(dataset) => dataset.surveysAttached
);
const surveysDataset = datasetToAttachSurveysOn
? {
type: "scatter",
label: "SURVEYS",
pointBackgroundColor: pointColor(selectedSurveyDate),
borderWidth: 1.5,
pointRadius: 5,
borderColor: SURVEY_CHART_POINT_BORDER_COLOR,
data: datasetToAttachSurveysOn.data
.filter(
(item) =>
!isNil(item.value) &&
surveyDates.some(
(surveyDate) =>
isNumber(surveyDate) && sameDay(surveyDate, item.timestamp)
)
)
.map(
({ timestamp, value }) => ({ x: timestamp, y: value } as ChartPoint)
),
}
: undefined;
return [
...(surveysDataset ? [surveysDataset] : []),
...(processedDatasets || []),
];
}
Example #25
Source File: index.tsx From fishbowl with MIT License | 5 votes |
function CardSubmission() {
const currentGame = React.useContext(CurrentGameContext)
const currentPlayer = React.useContext(CurrentPlayerContext)
const numSubmitted = filter(
currentGame.cards,
(card) => card.player_id === currentPlayer.id
).length
const [cardSubmissionState, setCardSubmissionState] = React.useState<
CardSubmissionState
>(
numSubmitted === currentGame.num_entries_per_player
? CardSubmissionState.Waiting
: CardSubmissionState.Submitting
)
React.useEffect(() => {
if (
currentGame.num_entries_per_player &&
numSubmitted < currentGame.num_entries_per_player
) {
setCardSubmissionState(CardSubmissionState.Submitting)
}
}, [numSubmitted])
return (
<Grid
container
direction="column"
justify="center"
alignItems="center"
spacing={2}
>
{cardSubmissionState === CardSubmissionState.Submitting ? (
<SubmissionForm
onSubmit={() => setCardSubmissionState(CardSubmissionState.Waiting)}
/>
) : (
<WaitingForSubmissions />
)}
</Grid>
)
}
Example #26
Source File: index.tsx From next-basics with GNU General Public License v3.0 | 5 votes |
// istanbul ignore next
private _handleSelectAll = (
selected: boolean,
selectedRows: Record<string, any>[],
changeRows: Record<string, any>[]
): void => {
this._selected = selected;
this._isInSelect = true;
const rowKey =
this.rowKey ?? this._fields.rowKey ?? this.configProps?.rowKey;
if (this.selectAllChildren) {
const allParentKeys = map(this._dataSource, rowKey);
const changedParentRows = changeRows.filter((v) =>
allParentKeys.includes(v[rowKey])
);
const toChangedChildrenKeys = flatten(
map(changedParentRows, (r) =>
map(this._getSelectedRowsWithChildren(r), (cr) => cr[rowKey])
)
);
const allChildren = flatten(
map(changedParentRows, (r) =>
map(this._getSelectedRowsWithChildren(r), (cr) => cr)
)
);
this._allChildren = allChildren;
if (!this.autoSelectParentWhenAllChildrenSelected) {
if (selected) {
this._disabledChildrenKeys = uniq(
this._disabledChildrenKeys.concat(toChangedChildrenKeys)
);
} else {
// disabled children in changeRows should be removed
this._disabledChildrenKeys = this._disabledChildrenKeys.filter(
(v) => !toChangedChildrenKeys.includes(v)
);
}
}
}
if (this.storeCheckedByUrl && !!rowKey) {
this._updateUrlChecked(map(changeRows, rowKey), selected);
}
};
Example #27
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
getFilterOptions = (options: IOption[], searchValue: string | undefined) => {
return filter(options, (_op) => (_op.label || '').toLowerCase().includes((searchValue || '').toLowerCase()));
}
Example #28
Source File: mySql-builder.service.ts From EDA with GNU Affero General Public License v3.0 | 5 votes |
public normalQuery(columns: string[], origin: string, dest: any[], joinTree: any[], grouping: any[], tables: Array<any>, limit: number): any {
let o = tables.filter(table => table.name === origin).map(table => { return table.query ? table.query : table.name })[0];
let myQuery = `SELECT ${columns.join(', ')} \nFROM ${o}`;
//to WHERE CLAUSE
const filters = this.queryTODO.filters.filter(f => {
const column = this.findColumn(f.filter_table, f.filter_column);
return column.computed_column != 'computed_numeric';
});
//TO HAVING CLAUSE
const havingFilters = this.queryTODO.filters.filter(f => {
const column = this.findColumn(f.filter_table, f.filter_column);
return column.computed_column == "computed_numeric";
});
// JOINS
const joinString = this.getJoins(joinTree, dest, tables);
joinString.forEach(x => {
myQuery = myQuery + '\n' + x;
});
// WHERE
myQuery += this.getFilters(filters, 'where');
// GroupBy
if (grouping.length > 0) {
myQuery += '\ngroup by ' + grouping.join(', ');
}
//HAVING
myQuery += this.getHavingFilters(havingFilters, 'having');
// OrderBy
const orderColumns = this.queryTODO.fields.map(col => {
let out;
if (col.ordenation_type !== 'No' && col.ordenation_type !== undefined) {
out = `\`${col.display_name}\` ${col.ordenation_type}`
} else {
out = false;
}
return out;
}).filter(e => e !== false);
const order_columns_string = orderColumns.join(',');
if (order_columns_string.length > 0) {
myQuery = `${myQuery}\norder by ${order_columns_string}`;
}
if (limit) myQuery += `\nlimit ${limit}`;
return myQuery;
}