lodash#find JavaScript Examples
The following examples show how to use
lodash#find.
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: game.js From flatris-LAB_V1 with MIT License | 6 votes |
// This function can have three responses:
// - 0, which means the action points to game state
// - <0, which means the action is from the past and will be discarded
// - >0, which means the action is detached and backfill is required
export function getGameActionOffset(game: Game, action: GameAction): number {
// There's no previous player action to follow when user just joined
if (action.type === 'JOIN_GAME') {
return 0;
}
const { userId, actionId, prevActionId } = action.payload;
const player = find(game.players, p => p.user.id === userId);
// Sometimes we get actions from players that aren't found in the state
// snapshot, because it's from a time before they joined
if (!player) {
return actionId;
}
return prevActionId - player.lastActionId;
}
Example #2
Source File: cadastrapp.js From mapstore2-cadastrapp with GNU General Public License v3.0 | 6 votes |
/**
* Toggles selection of one parcelle, if present
* @param {object} currentSelection current selection object
* @param {string} parcelle the Id of the parcelle
*/
function toggleSelection(currentSelection, parcelle) {
if (find(currentSelection.data, {parcelle})) {
const isSelectedIndex = currentSelection.selected.indexOf(parcelle);
let selected = currentSelection.selected;
if (isSelectedIndex >= 0) {
selected = selected.filter(v => v !== parcelle);
} else {
selected = [...selected, parcelle];
}
return {
...currentSelection,
selected
};
}
return currentSelection;
}
Example #3
Source File: CurrencyFormat.js From web with MIT License | 6 votes |
getPrice = (pricing, isDiscount, location) => {
let value = 0;
let price;
if (location) {
price = find(pricing, { country: location.country });
}
if (!price) {
// if no country, use USD as default
price = find(pricing, { country: 'United States of America' });
}
if (price) {
value = isDiscount ? price.discountPrice : price.price;
}
return value;
}
Example #4
Source File: MappingProfileDetailsRoute.js From ui-data-export with Apache License 2.0 | 6 votes |
MappingProfileDetailsRoute = ({
resources: {
mappingProfile,
jobProfiles,
},
allTransformations,
mutator: { mappingProfile: { DELETE } },
history,
match: { params },
location,
onCancel,
}) => {
// `find` is used to make sure the matched job profile, mapping profile are displayed to avoid
// the flickering because of the disappearing of the previous and appearing of the new ones
// TODO: try `useManifest` hook once it is ready to avoid that
const mappingProfileRecord = find([get(mappingProfile, 'records.0', {})], { id: params.id });
const isProfileUsed = Boolean(find([get(jobProfiles, 'records.0', {})], { mappingProfileId: params.id }));
const isDefaultProfile = mappingProfileRecord?.default;
return (
<MappingProfileDetails
allTransformations={allTransformations}
mappingProfile={mappingProfileRecord}
isProfileUsed={isProfileUsed}
isDefaultProfile={isDefaultProfile}
isLoading={!mappingProfileRecord || (!isDefaultProfile && !jobProfiles.hasLoaded)}
onEdit={() => history.push(`/settings/data-export/mapping-profiles/edit/${params.id}${location.search}`)}
onDuplicate={() => history.push(`/settings/data-export/mapping-profiles/duplicate/${params.id}${location.search}`)}
onCancel={onCancel}
onDelete={() => DELETE({ id: mappingProfileRecord?.id })}
/>
);
}
Example #5
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
@Bind()
handleTabChange(activeKey) {
const { component, currentEditField } = this.props;
const { fields = [] } = component;
const field = find(fields, f => f.fieldName === activeKey);
if (field && currentEditField !== field) {
this.handleActiveField(field);
}
}
Example #6
Source File: node-details-table.js From ThreatMapper with Apache License 2.0 | 6 votes |
function getNodeValue(node, header) {
const fieldId = header && header.id;
if (fieldId !== null) {
let field = union(node.metrics, node.metadata).find(f => f.id === fieldId);
if (field) {
if (isIP(header)) {
// Format the IPs so that they are sorted numerically.
return ipToPaddedString(field.value);
} if (isNumber(header)) {
return parseFloat(field.value);
}
return field.value;
}
if (node.parents) {
field = node.parents.find(f => f.topologyId === fieldId);
if (field) {
return field.label;
}
}
if (node[fieldId] !== undefined && node[fieldId] !== null) {
return node[fieldId];
}
}
return null;
}
Example #7
Source File: LegalForm.js From hzero-front with Apache License 2.0 | 6 votes |
isChinaCountry(countryId) {
const { company = {} } = this.props;
const { countryList = [] } = company;
if (!isEmpty(countryId)) {
const china = find(countryList, { countryId });
if (!isUndefined(china)) {
return china.countryCode === 'CN';
}
}
return false;
}
Example #8
Source File: node-details-table.js From ThreatMapper with Apache License 2.0 | 6 votes |
function getNodeValue(node, header) {
const fieldId = header && header.id;
if (fieldId !== null) {
let field = union(node.metrics, node.metadata).find(f => f.id === fieldId);
if (field) {
if (isIP(header)) {
// Format the IPs so that they are sorted numerically.
return ipToPaddedString(field.value);
} if (isNumeric(header)) {
return parseFloat(field.value);
}
return field.value;
}
if (node.parents) {
field = node.parents.find(f => f.topologyId === fieldId);
if (field) {
return field.label;
}
}
if (node[fieldId] !== undefined && node[fieldId] !== null) {
return node[fieldId];
}
}
return null;
}
Example #9
Source File: UserGroupModal.js From hzero-front with Apache License 2.0 | 6 votes |
@Bind()
handleEditModalOk() {
const { userRecord = {} } = this.props;
const { dataSource = [], defaultGroupId } = this.state;
const memberGroupList = [];
const validateDataSource = getEditTableData(dataSource);
validateDataSource.forEach(r => {
const newGroup = {
assignId: r.assignId,
defaultFlag: r.userGroupId === defaultGroupId ? 1 : 0,
groupCode: r.groupCode,
groupName: r.groupName,
tenantId: userRecord.organizationId,
tenantName: userRecord.tenantName,
userGroupId: r.userGroupId,
userId: userRecord.id,
_token: r._token,
objectVersionNumber: r.objectVersionNumber,
};
const oldR = find(dataSource, or => or.userGroupId === r.userGroupId);
if (
oldR._status === 'create' ||
(oldR._status === 'update' && oldR.defaultFlag !== newGroup.defaultFlag)
) {
memberGroupList.push(newGroup);
}
});
if (dataSource.length !== 0 && dataSource.length !== validateDataSource.length) {
// 用户组校验 失败
return;
}
const { onOk } = this.props;
const saveData = {
userId: userRecord.id,
memberGroupList,
};
onOk(saveData);
}
Example #10
Source File: createDataLoaders.js From rate-repository-api with MIT License | 6 votes |
createUserRepositoryReviewExistsLoader = () =>
new DataLoader(
async userIdRepositoryIdTuples => {
const userIds = userIdRepositoryIdTuples.map(([userId]) => userId);
const repositoryIds = userIdRepositoryIdTuples.map(
([, repositoryId]) => repositoryId,
);
const reviews = await Review.query()
.whereIn('repositoryId', repositoryIds)
.andWhere(qb => qb.whereIn('userId', userIds))
.select('repositoryId', 'userId');
return userIdRepositoryIdTuples.map(([userId, repositoryId]) => {
return !!reviews.find(
r => r.userId === userId && r.repositoryId === repositoryId,
);
});
},
{
cacheKeyFn: jsonCacheKeyFn,
},
)
Example #11
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
@Bind()
cancel(record) {
const { dataSource, editingRows } = this.state;
const defaultItem = editingRows.find(o => o.key === record.key);
this.setState({
dataSource: isInteger(record.key)
? dataSource.map(n => (n.key === defaultItem.key ? defaultItem : n))
: dataSource.filter(o => o.key !== record.key),
editingRows: editingRows.filter(o => o.key !== record.key),
});
}
Example #12
Source File: createDataLoaders.js From rate-repository-api with MIT License | 6 votes |
createModelLoader = Model =>
new DataLoader(
async ids => {
const idColumns = isArray(Model.idColumn)
? Model.idColumn
: [Model.idColumn];
const camelCasedIdColumns = idColumns.map(id => camelCase(id));
const results = await Model.query().findByIds(ids);
return ids.map(
id =>
find(
results,
zipObject(camelCasedIdColumns, isArray(id) ? id : [id]),
) || null,
);
},
{
cacheKeyFn: jsonCacheKeyFn,
},
)
Example #13
Source File: game.js From flatris-LAB_V1 with MIT License | 6 votes |
export function getPlayer(game: Game, userId: UserId): Player {
const player = find(game.players, p => p.user.id === userId);
if (!player) {
throw new Error(`Player with userId ${userId} does not exist`);
}
return player;
}
Example #14
Source File: createDataLoaders.js From rate-repository-api with MIT License | 6 votes |
createUserReviewCountLoader = () =>
new DataLoader(async userIds => {
const reviews = await Review.query()
.whereIn('userId', userIds)
.count('*', { as: 'reviewsCount' })
.groupBy('userId')
.select('userId');
return userIds.map(id => {
const review = reviews.find(({ userId }) => userId === id);
return review ? review.reviewsCount : 0;
});
})
Example #15
Source File: index.js From hzero-front with Apache License 2.0 | 6 votes |
/**
* deal component attribute change
*/
handleComponentValuesChange(props, changeValues, allValues) {
// 使用 allValues 重写 component 的属性
// use allValues override component's props
const { component, onRefresh } = this.props;
const { validateFields } = this.editFormRef.current || {};
if (validateFields) {
validateFields(err => {
if (!err) {
const newConfig = [];
// common component's prop;
component.templateCode = allValues.templateCode;
component.description = allValues.description;
component.enabledFlag = allValues.enabledFlag;
if (isNumber(allValues.style.marginBottom)) {
newConfig.push({
[attributeNameProp]: 'style.marginBottom',
[attributeValueProp]: allValues.style.marginBottom,
[attributeTypeProp]: DataType.Number,
});
}
const prevComponentConfigs = component.config;
component.config = newConfig.map(componentConfig => {
const prevComponentConfig = find(
prevComponentConfigs,
prevC => prevC[attributeNameProp] === componentConfig[attributeNameProp]
);
return { ...prevComponentConfig, ...componentConfig };
});
if (isFunction(onRefresh)) {
onRefresh();
}
}
});
}
}
Example #16
Source File: api.js From flatris-LAB_V1 with MIT License | 6 votes |
function getBackfillRes(req: BackfillRequest): BackfillResponse {
const { gameId, players } = req;
const actions = gameActions[gameId].filter(action => {
const player = find(
players,
({ userId }) => userId === action.payload.userId
);
return (
// Include all actions of users that the user who requested the backfill
// isn't aware of (ie. users that joined since last backfill)
!player || (player && action.payload.actionId > player.from)
);
});
return { gameId, actions };
}
Example #17
Source File: Chart.js From covid19 with MIT License | 5 votes |
countryFromKey = (label, countries) =>
find(countries, ['iso', label.toString().slice(0, 3)]).name
Example #18
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
@Bind()
handleRowSelectionChange(selectStatus, selectedRows = []) {
// TODO: 要做复杂的判断
const { rowSelection, dataSource = [] } = this.state;
const prevRowSelection = rowSelection || {
onChange: this.handleRowSelectionChange,
onSelectAll: this.handleRowSelectionChange.bind(this, 'all_none'),
getCheckboxProps: this.getCheckboxProps,
};
const { selectedRowKeys: preSelectedRowKeys = [] } = prevRowSelection;
const diffObj = {
diffLen: selectedRows.length - preSelectedRowKeys.length,
};
const nextPartialState = {
rowSelection: {
...prevRowSelection,
selectedRowKeys: [],
onChange: this.handleRowSelectionChange,
onSelectAll: this.handleRowSelectionChange.bind(this, 'all_none'),
getCheckboxProps: this.getCheckboxProps,
},
selectedRows: [],
};
if (selectStatus === 'all_none') {
// 全选或者取消全选
if (selectedRows) {
diffObj.selectAllStatus = 'all';
} else {
diffObj.selectAllStatus = 'none';
}
}
// 选中项目新增
// 如果是选中的父节点, 子节点对应选中
// 新增额外的
nextPartialState.dataSource = this.travelDataSource(dataSource, false, {
hitFunc(record) {
if (diffObj.selectAllStatus === 'all') {
return true;
}
if (diffObj.selectAllStatus === 'none') {
return false;
}
return !!find(selectedRows, r => r.textId === record.textId);
},
travelFunc(record, { hit, hitParent }) {
if (hit || hitParent) {
nextPartialState.selectedRows.push(record);
nextPartialState.rowSelection.selectedRowKeys.push(record.textId);
}
return !!hitParent;
},
travelDeep: true,
});
this.setState(nextPartialState);
}
Example #19
Source File: StatsCell.js From covid19 with MIT License | 5 votes |
Success = ({ countries = [], country = 'usa' }) => {
// Calculate stats
const [counts, setCounts] = useState([])
const stat = (key) =>
commaNumber(last(map(orderBy(counts, 'date.date'), key)))
useEffect(() => {
setCounts(find(countries, ['iso', country])?.dailyCounts)
}, [country])
return (
<div>
<section>
<StatChart data={counts} dataKey="newCases" color="green" />
<Stat value={stat('newCases')} label="New cases" />
</section>
<section>
<StatChart data={counts} dataKey="currentlyInfected" color="yellow" />
<Stat value={stat('currentlyInfected')} label="Currently infected" />
</section>
<section>
<StatChart data={counts} dataKey="totalCases" color="orange" />
<Stat value={stat('totalCases')} label="Confirmed cases" />
</section>
<section>
<StatChart data={counts} dataKey="totalDeaths" color="red" />
<Stat value={stat('totalDeaths')} label="Confirmed deaths" />
</section>
<style jsx>{`
div {
display: grid;
grid-gap: 1rem;
margin-top: 2rem;
}
@media (min-width: 48em) {
div {
grid-template-columns: repeat(4, 1fr);
}
}
section {
position: relative;
min-height: 8rem;
}
section :global(.recharts-responsive-container) {
position: absolute !important;
top: 0;
left: 0;
right: 0;
}
`}</style>
</div>
)
}
Example #20
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
@Bind()
save() {
const { handleSave = e => e, roleDatasource } = this.props;
const { dataSource = [], editingRows = [] } = this.state;
const tableRowForms = this.tableRowForms
.map(o => {
const item = editingRows.find(n => o.key === n.key);
return !isEmpty(item) ? { ...o, rowData: item } : false;
})
.filter(Boolean);
Promise.all(
tableRowForms.map(
o =>
new Promise((resolve, rejcet) => {
const { validateFields = () => {} } = o.row || {};
validateFields((error, values) => {
if (!isEmpty(error)) {
rejcet(error);
} else {
resolve({ ...o.rowData, ...values });
}
});
})
)
)
.then((result = []) => {
const data = dataSource.map(n => {
const newItem = result.find(o => o.key === n.key);
const item = !isEmpty(newItem) ? newItem : n;
const { id, assignLevel, assignLevelValue } = item;
return {
memberId: id,
assignLevel,
assignLevelValue,
roleId: roleDatasource.id,
};
});
if (!isEmpty(data)) {
handleSave(data, false, () => {
notification.success({
message: intl.get(`hzero.common.notification.success.save`).d('保存成功'),
});
this.onDrawerClose();
});
}
})
.catch(e => {
window.console.warn(e);
});
// if (!isEmpty(dataSource.filter(o => !isEmpty(o.error)))) {
// return;
// }
}
Example #21
Source File: Layout.js From web with MIT License | 5 votes |
IndexLayout = ({ children, hideHeader }) => {
const updateLocation = useStoreActions(
actions => actions.user.updateLocation,
);
useEffect(() => {
// get geo location
axios
.get('https://extreme-ip-lookup.com/json/')
.then(response => {
// handle success
const { data } = response;
if (data) {
const currentCurrency = find(currency, { code: data.countryCode });
updateLocation({
city: data.city,
country: data.country,
countryCode: data.countryCode,
region: data.region,
currency: currentCurrency ? currentCurrency.currency : '$',
currencyCode: currentCurrency
? currentCurrency.currencyCode
: 'usd',
});
}
})
.catch(error => {
// handle error
console.log('unable to fetch ip data', error);
});
}, []);
return (
<ThemeProvider theme={theme}>
<>
<Helmet>
<title>{config.siteName}</title>
<meta charSet="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta description={config.description} />
</Helmet>
<GlobalStyle />
<StaticQuery
query={query}
render={data => {
const home = data.sanitySiteSettings;
return (
<>
<TopBar />
{!hideHeader && <Header />}
<Container>{children}</Container>
<Footer home={home} />
</>
);
}}
/>
</>
</ThemeProvider>
);
}
Example #22
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
/**
* deal field's attribute change
*/
handleFieldValuesChange(props, changeValues, allValues) {
// 使用 allValues 重写 field 的属性
const { field, component, onRefresh } = this.props;
const { validateFields } = this.editFormRef.current || {};
if (validateFields) {
validateFields(err => {
if (!err) {
const newConfig = [];
field[fieldLabelProp] = allValues[fieldLabelProp];
field[fieldNameProp] = allValues[fieldNameProp];
// fields's common prop;
field.requiredFlag = allValues.requiredFlag;
// 不要 visiableFlag 字段了
// field.visiableFlag = allValues.visiableFlag;
// todo 字段的 enabledFlag 不能编辑了
// field.enabledFlag = allValues.enabledFlag;
field.description = allValues.description;
field.align = allValues.align;
if (has(changeValues, 'autoSize')) {
// autoSize 有更改才改变 width
if (allValues.autoSize) {
field.width = 0; // can set field width in right only when autoSize is 0
} else {
field.width = autoSizeWidth;
}
}
const getConfigOfPropValuesFunc = `get${field.componentType}ConfigOfPropValues`;
if (this[getConfigOfPropValuesFunc]) {
this[getConfigOfPropValuesFunc](allValues, newConfig);
}
const prevFieldConfigs = field.config;
field.config = newConfig.map(fieldConfig => {
const prevFieldConfig = find(
prevFieldConfigs,
prevC => prevC[attributeNameProp] === fieldConfig[attributeNameProp]
);
return { ...prevFieldConfig, ...fieldConfig };
});
const newField = field; // { ...field };
// 更新 feild 在 component 中的引用
let fieldRefUpdate = false;
forEach(component.fields, (f, index) => {
if (f === field) {
fieldRefUpdate = true;
component.fields[index] = newField;
return false;
}
return !fieldRefUpdate;
});
if (isFunction(onRefresh)) {
onRefresh();
}
}
});
}
}
Example #23
Source File: index.jsx From mui-phone-input-ssr with MIT License | 5 votes |
constructor(props) {
super(props);
let filteredCountries = countryData.allCountries;
if (props.disableAreaCodes) filteredCountries = this.deleteAreaCodes(filteredCountries);
if (props.regions) filteredCountries = this.filterRegions(props.regions, filteredCountries);
const onlyCountries = this.excludeCountries(
this.getOnlyCountries(props.onlyCountries, filteredCountries), props.excludeCountries,
);
const preferredCountries = filter(filteredCountries, (country) => some(props.preferredCountries, (preferredCountry) => preferredCountry === country.iso2));
const inputNumber = props.value || '';
let countryGuess;
if (inputNumber.length > 1) {
// Country detect by value field
countryGuess = this.guessSelectedCountry(inputNumber.replace(/\D/g, '').substring(0, 6), onlyCountries, props.defaultCountry) || 0;
} else if (props.defaultCountry) {
// Default country
countryGuess = find(onlyCountries, { iso2: props.defaultCountry }) || 0;
} else {
// Empty params
countryGuess = 0;
}
const countryGuessIndex = findIndex(this.allCountries, countryGuess);
const dialCode = (
inputNumber.length < 2
&& countryGuess
&& !startsWith(inputNumber.replace(/\D/g, ''), countryGuess.dialCode)
) ? countryGuess.dialCode : '';
const formattedNumber = (inputNumber === '' && countryGuess === 0) ? ''
: this.formatNumber(
(props.disableCountryCode ? '' : dialCode) + inputNumber.replace(/\D/g, ''),
countryGuess.name ? countryGuess.format : undefined,
);
this.state = {
formattedNumber,
placeholder: props.placeholder,
onlyCountries,
preferredCountries,
defaultCountry: props.defaultCountry,
selectedCountry: countryGuess,
highlightCountryIndex: countryGuessIndex,
queryString: '',
freezeSelection: false,
debouncedQueryStingSearcher: debounce(this.searchCountry, 100),
anchorEl: null,
};
}
Example #24
Source File: DemarcheSectionReadOnly.js From datapass with GNU Affero General Public License v3.0 | 5 votes |
valueToLabel = (key, availableScopes) => {
const scope = find(availableScopes, { value: key });
if (scope) {
return scope.label;
} else {
return key;
}
}
Example #25
Source File: country.js From rakning-c19-app with MIT License | 5 votes |
getCountryDataByCode(iso2) {
return find(this.getAll(), country => country.iso2 === iso2);
}
Example #26
Source File: game.js From flatris-LAB_V1 with MIT License | 5 votes |
export function getOtherPlayer(game: Game, curPlayer: Player): ?Player {
// NOTE: This only works with max 2 players per game
return find(game.players, p => p !== curPlayer);
}
Example #27
Source File: index.js From hzero-front with Apache License 2.0 | 5 votes |
/**
* deal field's attribute change
*/
handleFieldValuesChange(props, changeValues, allValues) {
// 使用 allValues 重写 field 的属性
const { field, component, onRefresh } = this.props;
const { validateFields } = this.editFormRef.current || {};
if (validateFields) {
validateFields(err => {
if (!err) {
const newConfig = [];
field[fieldLabelProp] = allValues[fieldLabelProp];
field[fieldNameProp] = allValues[fieldNameProp];
// fields's common prop;
// field.requiredFlag = allValues.requiredFlag;
// // todo 字段的 visibleFlag 不使用了
// field.visiableFlag = allValues.visiableFlag;
// // todo 字段的 enabledFlag 不能编辑了
// field.enabledFlag = allValues.enabledFlag;
field.description = allValues.description;
const getConfigOfPropValuesFunc = `get${field.componentType}ConfigOfPropValues`;
if (this[getConfigOfPropValuesFunc]) {
this[getConfigOfPropValuesFunc](allValues, newConfig, field);
}
const prevFieldConfigs = field.config;
field.config = newConfig.map(fieldConfig => {
const prevFieldConfig = find(
prevFieldConfigs,
prevC => prevC[attributeNameProp] === fieldConfig[attributeNameProp]
);
return { ...prevFieldConfig, ...fieldConfig };
});
const newField = field; // { ...field };
// 更新 feild 在 component 中的引用
let fieldRefUpdate = false;
forEach(component.fields, (f, index) => {
if (f === field) {
fieldRefUpdate = true;
component.fields[index] = newField;
return false;
}
return !fieldRefUpdate;
});
if (isFunction(onRefresh)) {
onRefresh();
}
}
});
}
}
Example #28
Source File: extractPoolRewardsFromUserDrips.js From v3-ui with MIT License | 5 votes |
extractPoolRewardsFromUserDrips = ({ poolAddresses, playerDrips }) => {
const dripTokens = playerDrips?.dripTokens || []
const balanceDrips = []
const volumeDrips = []
// const balanceDrips = playerDrips?.balanceDrips.filter(drip => {
// return poolAddresses.includes(drip.balanceDrip.prizePool.id)
// })
// const volumeDrips = playerDrips?.volumeDrips.filter(drip => {
// return poolAddresses.includes(drip.volumeDrip.prizePool.id)
// })
const playerRewards = {
allDrips: [],
balance: [],
volume: [],
refVolume: []
}
dripTokens.forEach((drip) => {
const [comptroller, dripToken, player] = drip.id.split('-')
const dripTokenData = { name: 'Unknown', symbol: 'UNK' }
// const dripTokenData = DRIP_TOKENS[dripToken] || {name: 'Unknown', symbol: 'UNK'}
let finalDripData = {
dripToken: {
address: dripToken,
name: dripTokenData.name,
symbol: dripTokenData.symbol
},
...drip
}
// Balance Drips
const balDrip = find(balanceDrips, (bd) => bd.balanceDrip.dripToken === dripToken)
if (balDrip) {
finalDripData = {
...finalDripData,
...balDrip
}
playerRewards.balance.push({ ...finalDripData })
}
// Volume Drips
const volDrip = find(volumeDrips, (vd) => vd.volumeDrip.dripToken === dripToken)
if (volDrip) {
finalDripData = {
...finalDripData,
...volDrip
}
if (volDrip.volumeDrip.referral) {
playerRewards.refVolume.push({ ...finalDripData })
} else {
playerRewards.volume.push({ ...finalDripData })
}
}
playerRewards.allDrips.push({ ...finalDripData })
})
return playerRewards
}
Example #29
Source File: index.js From hzero-front with Apache License 2.0 | 4 votes |
/**
* deal field's attribute change
*/
handleFieldValuesChange(props, changeValues, allValues) {
// 使用 allValues 重写 field 的属性
const { field, component, onRefresh } = this.props;
const { validateFields } = this.editFormRef.current || {};
if (validateFields) {
validateFields(err => {
if (!err) {
const newConfig = [];
field[fieldLabelProp] = allValues[fieldLabelProp];
field[fieldNameProp] = allValues[fieldNameProp];
// fields's common prop;
field.requiredFlag = allValues.requiredFlag;
// enabledFlag 是用来字段禁用的
field.enabledFlag = allValues.enabledFlag;
if (isBoolean(allValues.labelDisplayFlag)) {
newConfig.push({
[attributeNameProp]: 'labelDisplayFlag',
[attributeValueProp]: allValues.labelDisplayFlag,
[attributeTypeProp]: DataType.Boolean,
});
}
if (isString(allValues.description)) {
newConfig.push({
[attributeNameProp]: 'description',
[attributeValueProp]: allValues.description,
[attributeTypeProp]: DataType.String,
});
}
if (isString(allValues.placeholder)) {
newConfig.push({
[attributeNameProp]: 'placeholder',
[attributeValueProp]: allValues.placeholder,
[attributeTypeProp]: DataType.String,
});
}
if (isString(allValues.onChange)) {
newConfig.push({
[attributeNameProp]: 'onChange',
[attributeValueProp]: allValues.onChange,
[attributeTypeProp]: DataType.String,
});
}
const FieldComponent = fieldComponents[field.componentType];
if (FieldComponent) {
FieldComponent.getConfigOfPropValues(allValues, newConfig);
} else {
const getConfigOfPropValuesFunc = `get${field.componentType}ConfigOfPropValues`;
if (this[getConfigOfPropValuesFunc]) {
this[getConfigOfPropValuesFunc](allValues, newConfig);
}
}
const prevFieldConfigs = field.config;
field.config = newConfig.map(fieldConfig => {
const prevFieldConfig = find(
prevFieldConfigs,
prevC => prevC[attributeNameProp] === fieldConfig[attributeNameProp]
);
return { ...prevFieldConfig, ...fieldConfig };
});
const newField = field; // { ...field };
// 更新 feild 在 component 中的引用
let fieldRefUpdate = false;
forEach(component.fields, (fArr, rowIndex) => {
forEach(fArr, (f, colIndex) => {
if (f === field) {
fieldRefUpdate = true;
component.fields[rowIndex][colIndex] = newField;
return false;
}
});
return !fieldRefUpdate;
});
if (isFunction(onRefresh)) {
onRefresh();
}
}
});
}
}