lodash#pick TypeScript Examples
The following examples show how to use
lodash#pick.
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: utilities.ts From react-native-jigsaw with MIT License | 7 votes |
export function extractBorderAndMarginStyles(
style: StyleProp<any>,
additionalBorderStyles?: string[],
additionalMarginStyles?: string[]
) {
const flatStyle = StyleSheet.flatten(style || {});
const borderStyles = pickBy(
pick(flatStyle, [
...borderStyleNames,
...(additionalBorderStyles ? additionalBorderStyles : []),
]),
identity
);
const marginStyles = pickBy(
pick(flatStyle, [
...marginStyleNames,
...(additionalMarginStyles ? additionalMarginStyles : []),
]),
identity
);
return { borderStyles, marginStyles };
}
Example #2
Source File: utils.ts From next-core with GNU General Public License v3.0 | 7 votes |
export function extractProviderContract(
context: Context,
doc: ApiDoc,
modelSeg: string
): ContractDoc {
return {
contract: `${context.serviceSeg}.${modelSeg}.${doc.name}`,
category: context.modelI18nMap.get("description"),
...pick(doc, [
"name",
"version",
"description",
"detail",
"endpoint",
"import",
"request",
"response",
"examples",
]),
} as ContractDoc;
}
Example #3
Source File: push-queue.ts From one-platform with MIT License | 6 votes |
export default async function setupPushJobs() {
console.log('[PushQueue] Initializing...');
/* Define jobs */
agenda.define(PUSH_JOB_NAME, async (job: Job) => {
const { notification } = job.attrs.data as PushNotificationJob;
const record = await getNotifications().insertOne({
...notification,
});
if (!record.acknowledged) {
throw new Error('Could not create notification');
}
const subscribers = await getSubscribers()
.find({
subscriptions: {
$elemMatch: {
...pick(notification, ['contentType', 'contentId', 'action']),
},
},
})
.toArray();
/* Push notifications via pubsub */
subscribers.map((subscriber) => {
pubsub.publish(subscriber._id, { notificationId: record.insertedId });
});
});
}
Example #4
Source File: helper.ts From sc2-planner with MIT License | 6 votes |
encodeSettings = (
settingsObject: Array<ISettingsElement>,
settingsDefaultValues: { [name: string]: number | string }
): string => {
// Strip away unwanted values
let strippedObject = settingsObject.map((item) => {
return pick(item, ["n", "v"])
})
// If they are default values, strip them away
strippedObject = strippedObject.filter((item) => {
return settingsDefaultValues[item.n] !== item.v
})
const jsonString = JSON.stringify(strippedObject)
const encoded = lzbase62.compress(jsonString)
return encoded
}
Example #5
Source File: postBuild.ts From askql with MIT License | 6 votes |
async function copyPackageJson() {
await pfs.writeFile(
'dist/package.json',
JSON.stringify(
pick(packageJson, propertiesToPreserveFromPackageJSON),
null,
2
)
);
console.log('Package.json was written to dist');
}
Example #6
Source File: generate-with-init.test.ts From openzeppelin-transpiler with MIT License | 6 votes |
test.before('gather solc input output', async t => {
const buildInfo = await getBuildInfo('0.6');
const solcInput = buildInfo.input;
const solcOutput = buildInfo.output as SolcOutput;
t.context.solcInputOutput = (...paths) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return [solcInput, solcOutput].map(x => mapValues(x, y => pick(y, paths))) as any;
};
});
Example #7
Source File: promise.ts From Adachi-BOT with MIT License | 6 votes |
export async function mysAvatarDetailInfoPromise(
uid: string,
avatar: number,
server: string,
cookie: string,
constellation: CharacterCon
): Promise<ApiType.Skills> {
const { retcode, message, data } = await api.getAvatarDetailInfo( uid, avatar, server, cookie );
if ( !ApiType.isAvatarDetail( data ) ) {
return Promise.reject( ErrorMsg.UNKNOWN );
}
return new Promise( async ( resolve, reject ) => {
if ( retcode !== 0 ) {
reject( ErrorMsg.FORM_MESSAGE + message );
return;
}
const skills = data.skillList
.filter( el => el.levelCurrent !== 0 && el.maxLevel !== 1 )
.map( el => {
const temp: ApiType.Skills[number] = pick( el, [ "name", "icon", "levelCurrent" ] );
constellation.upSkills.forEach( v => {
if ( temp.name === v.skillName && constellation.activedNum >= v.requirementNum ) {
temp.levelCurrent += v.level;
}
} );
if ( /^普通攻击·(.+?)/.test( temp.name ) ) {
temp.name = temp.name.slice( 5 );
}
return temp;
} );
resolve( skills );
} );
}
Example #8
Source File: tooltip.ts From S2 with MIT License | 6 votes |
mergeCellInfo = (cells: S2CellType[]): TooltipData[] => {
return map(cells, (stateCell) => {
const stateCellMeta = stateCell.getMeta();
return assign(
{},
stateCellMeta.query || {},
pick(stateCellMeta, ['colIndex', 'rowIndex']),
);
});
}
Example #9
Source File: utils.ts From aqualink-app with MIT License | 6 votes |
calculateSondeDataMeanValues = (
metrics: SondeMetricsKeys[],
timeSeriesData?: TimeSeriesData
) =>
mapValues(pick(timeSeriesData, map(metrics, camelCase)), (data) =>
meanBy(data?.sonde?.data, "value")
)
Example #10
Source File: JsonRulesEngineFactChecker.ts From backstage with Apache License 2.0 | 6 votes |
private static constructCheckResponse(
techInsightCheck: TechInsightJsonRuleCheck,
result: any,
) {
const returnable = {
id: techInsightCheck.id,
type: techInsightCheck.type,
name: techInsightCheck.name,
description: techInsightCheck.description,
factIds: techInsightCheck.factIds,
metadata: result.result
? techInsightCheck.successMetadata
: techInsightCheck.failureMetadata,
rule: { conditions: {} },
};
if ('toJSON' in result) {
// Results from json-rules-engine serialize "wrong" since the objects are creating their own serialization implementations.
// 'toJSON' should always be present in the result object but it is missing from the types.
// Parsing the stringified representation into a plain object here to be able to serialize it later
// along with other items present in the returned response.
const rule = JSON.parse(result.toJSON());
return { ...returnable, rule: pick(rule, ['conditions']) };
}
return returnable;
}
Example #11
Source File: helpers.ts From webapp with MIT License | 6 votes |
decodeRemoveLiquidity = (
rawEvent: RawEventResponse
): DecodedEvent<RemoveLiquidityEvent> => {
const decoded = web3.eth.abi.decodeLog(
removeLiquidityEventAbi,
rawEvent.data,
rawEvent.topics
);
const txHash = rawEvent.transactionHash;
const keys = removeLiquidityEventAbi.map(abi => abi.name);
const dynamic = pick(decoded, keys) as {
amount: string;
newBalance: string;
newSupply: string;
};
const [, trader, tokenAdded] = rawEvent.topics;
const blockNumber = String(web3.utils.toDecimal(rawEvent.blockNumber));
return {
id: txHash,
txHash,
blockNumber,
data: {
...dynamic,
trader: removeLeadingZeros(trader),
tokenRemoved: removeLeadingZeros(tokenAdded)
}
};
}
Example #12
Source File: LaunchpadService.ts From next-basics with GNU General Public License v3.0 | 6 votes |
getSitemapList() {
const curMicroApps = getRuntime().getMicroApps({ includeInternal: true });
const siteMapList = getRuntime().getLaunchpadSiteMap();
return siteMapList?.map((item) => ({
...item,
apps: (item.apps || []).map((row) => {
const find = curMicroApps.find((item) => item.id === row.id) || {};
return {
...row,
...pick(find, ["name", "icons", "localeName", "homepage"]),
};
}),
}));
}
Example #13
Source File: Kernel.ts From next-core with GNU General Public License v3.0 | 6 votes |
_dev_only_updateTemplatePreviewSettings(
appId: string,
templateId: string,
settings?: unknown
): void {
const { routes } = this.bootstrapData.storyboards.find(
(item) => item.app.id === appId
);
const previewPath = `\${APP.homepage}/_dev_only_/template-preview/${templateId}`;
const previewRouteIndex = routes.findIndex(
(route) => route.path === previewPath
);
const newPreviewRoute: RouteConf = {
path: previewPath,
bricks: [
{
brick: templateId,
...pick(settings, "properties", "events", "lifeCycle", "context"),
},
],
menu: false,
exact: true,
};
if (previewRouteIndex === -1) {
routes.unshift(newPreviewRoute);
} else {
routes.splice(previewRouteIndex, 1, newPreviewRoute);
}
}
Example #14
Source File: query-string.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
/**
* 设置参数到当前url上(非合并)
* @param search query对象
* @param keepParams 需要保留的query属性
* @param replace 是否用replace跳转
*/
export function setSearch(search?: { [prop: string]: any }, keepParams: string[] = [], replace?: boolean) {
const keepQuery = pick(parse(location.search), keepParams);
goTo(`${location.pathname}?${mergeSearch({ ...keepQuery, ...search }, true, true)}`, { replace });
}
Example #15
Source File: InputLang.tsx From gant-design with MIT License | 6 votes |
withLangSelect = compose(
defaultProps({
allowClear: true,
placeholder: '请输入文本',
onChange: () => { },
localeList: [],
}),
withProps(({ localeList }) => {
return {
language: localeList.length ? map(localeList, item => pick(item, ['locale', 'label'])) : defaultLocaleList,
}
}),
withState("currentLocale", "setCurrentLocale", ({ language, defalutLocale }) => defalutLocale || language[0].locale),
withHandlers({
onLocaleChange: ({ setCurrentLocale }) => (locale) => {
setCurrentLocale(locale)
}
})
)
Example #16
Source File: create-one-file.ts From js-client with MIT License | 6 votes |
makeCreateOneFile = (context: APIContext) => {
const updateOneFile = makeUpdateOneFile(context);
const getOneFile = makeGetOneFile(context);
const filesPath = '/api/files';
const url = buildURL(filesPath, { ...context, protocol: 'http' });
return async (data: CreatableFile): Promise<FileMetadata> => {
try {
const baseRequestOptions: HTTPRequestOptions = {
body: toFormData(data) as any,
};
const req = buildHTTPRequestWithAuthFromContext(context, baseRequestOptions);
const raw = await context.fetch(url, { ...req, method: 'POST' });
const rawRes = await parseJSONResponse<RawBaseFileMetadata>(raw);
const globalID = rawRes.GUID;
// !WARNING: Can't set all properties on file creation gravwell/gravwell#2506
const updateProps: Array<keyof CreatableFile> = ['globalID', 'groupIDs', 'isGlobal', 'labels'];
const needsUpdate = Object.keys(data).some(k => updateProps.includes(k as keyof CreatableFile));
if (needsUpdate) return updateOneFile({ ...pick(data, updateProps), id: globalID });
return getOneFile(globalID);
} catch (err) {
if (err instanceof Error) throw err;
throw Error('Unknown error');
}
};
}
Example #17
Source File: common.ts From ovineherd with Apache License 2.0 | 6 votes |
export function setStoreInfo(source: any) {
const { appInfo, orgInfo } = source
// 合并 组织与应用的设置信息
let custom = {
...orgInfo,
...appInfo,
}
if (!isAppIsolation(true)) {
custom = {
...orgInfo,
...pick(appInfo, ['title', 'logo']),
}
}
setStore(storeKey.appInfo, appInfo)
setStore(storeKey.orgInfo, orgInfo)
setStore(storeKey.siteCustom, custom)
setOvineConstants(appInfo.app_env_constants)
homePageId = appInfo.app_home_page_id || ''
store = getCacheStore()
}
Example #18
Source File: alerts.service.ts From office-hours with GNU General Public License v3.0 | 6 votes |
async removeStaleAlerts(alerts: AlertModel[]): Promise<Alert[]> {
const nonStaleAlerts = [];
for (const alert of alerts) {
// Might be one of the few usecases for ReasonML
switch (alert.alertType) {
case AlertType.REPHRASE_QUESTION:
const payload = alert.payload as RephraseQuestionPayload;
const question = await QuestionModel.findOne(payload.questionId);
const queue = await QueueModel.findOne(payload.queueId, {
relations: ['staffList'],
});
const isQueueOpen = await queue?.checkIsOpen();
if (question.closedAt || !isQueueOpen) {
alert.resolved = new Date();
await alert.save();
} else {
nonStaleAlerts.push(
pick(alert, ['sent', 'alertType', 'payload', 'id']),
);
}
break;
}
}
return nonStaleAlerts;
}
Example #19
Source File: init.ts From free-swagger with MIT License | 6 votes |
export function init(): void {
const packageJsonPath = path.resolve(__dirname, '../../package.json')
const pkg = JSON.parse(fse.readFileSync(packageJsonPath, 'utf-8'))
commander
.version(pkg.version)
.usage('')
.option('-r --reset', '重置为默认配置', () => {
rc.reset()
console.log(chalk.green('重置配置项成功'))
})
.option('-s --show', '显示当前配置', () => {
rc.show()
})
.option('-e --edit', '修改当前配置', () => {
rc.edit()
})
.option('-m --mock', '全量生成 mock 数据', async () => {
await prompt(mockQuestion)
await mock(rc.createMockParams())
})
.option('-c, --config', '以配置项启动 free-swagger-cli', async () => {
await prompt(apiQuestion)
await freeSwagger(rc.createFreeSwaggerParams(), {
onChooseApi: async ({ paths }) =>
pick(paths, ...(await chooseApi(paths))),
})
})
// 无参数启动
.action(async ({ rawArgs }) => {
if (!global.__DEV__ && rawArgs[2]) return
await prompt([source])
await freeSwagger(rc.createFreeSwaggerParams())
})
.allowUnknownOption()
.parse(process.argv)
}
Example #20
Source File: http-fetch.ts From openapi-generator-typescript with MIT License | 6 votes |
openApiClient = warpHttpClient<OpenApiOperationsDictionary>(
openApiDocs
)<typeof FetchHttpClientURI>(
({ getUrl, method, params, parameterNames }, body, config) => {
const queryParams = pick(params, parameterNames.query);
const url = getUrl({ params });
return fetch(url + '?' + querystring.stringify(queryParams), {
method,
body: JSON.stringify(body),
}).then(x => x.json());
}
)
Example #21
Source File: email-queue.ts From one-platform with MIT License | 5 votes |
export default async function setupEmailJobs() {
console.log('[EmailQueue] Initializing...');
/* Define jobs */
agenda.define(EMAIL_JOB_NAME, async (job: Job) => {
const { notification, additionalRecipients } = job.attrs
.data as EmailNotificationJob;
const record = await getNotifications().insertOne({
...notification,
});
if (!record.acknowledged) {
throw new Error('Could not create notification');
}
const subscribers = await getSubscribers()
.find({
subscriptions: {
$elemMatch: {
...pick(notification, ['contentType', 'contentId', 'action']),
},
},
})
.toArray();
const recipients = subscribers
.map((subscriber) => `${subscriber.name} <${subscriber.email}>`)
.join(',');
if (!Boolean(recipients)) {
return;
}
const copyTo = additionalRecipients?.length
? additionalRecipients
.map((recipient) => `${recipient.name ?? ''} <${recipient.email}>`)
.join(',')
: undefined;
/* Send email using the nodemailer transport */
await emailTransport.sendMail({
from: EMAIL_NOTIFICATION_SENDER,
to: recipients,
cc: copyTo,
messageId: notification.contentId ?? record.insertedId.toString(),
subject: notification.payload.subject,
text: notification.payload.body,
});
});
}
Example #22
Source File: gameService.ts From project-tauntaun with GNU Lesser General Public License v3.0 | 5 votes |
function sendRouteInsertAt(group: Group, atWp: Point, newWp: Point): void {
sendMessage('group_route_insert_at', {
...pick(group, ['id']),
new: pick(newWp, ['lat', 'lon']),
at: pick(atWp, ['lat', 'lon'])
});
}
Example #23
Source File: block.service.ts From amplication with Apache License 2.0 | 5 votes |
private async cloneVersionData(
sourceVersionId: string,
targetVersionId: string
): Promise<void> {
const sourceVersion = await this.prisma.blockVersion.findUnique({
where: {
id: sourceVersionId
}
});
if (!sourceVersion) {
throw new Error(`Can't find source (Block Version ${sourceVersionId})`);
}
let targetVersion = await this.prisma.blockVersion.findUnique({
where: {
id: targetVersionId
}
});
if (!targetVersion) {
throw new Error(`Can't find target (Block Version ${targetVersionId})`);
}
const names = pick(sourceVersion, ['displayName', 'description']);
//update the target version with its fields, and the its parent block
targetVersion = await this.prisma.blockVersion.update({
where: {
id: targetVersionId
},
data: {
//when the source target is flagged as deleted (commit on DELETE action), do not update the parent block
block: sourceVersion.deleted
? undefined
: {
update: {
...names,
deletedAt: null
}
},
...names,
settings: sourceVersion.settings,
inputParameters: sourceVersion.inputParameters,
outputParameters: sourceVersion.outputParameters
}
});
}
Example #24
Source File: helpers.ts From aqualink-app with MIT License | 5 votes |
mapMetrics = <T>(
data: Partial<Record<MetricsKeys, T>>
): Partial<Record<Metrics, T>> =>
mapKeys(pick(data, metricsKeysList), (_, key) => camelCase(key)) as Partial<
Record<Metrics, T>
>
Example #25
Source File: helpers.ts From webapp with MIT License | 5 votes |
decodeConversionEvent = (
rawEvent: RawEventResponse
): DecodedEvent<ConversionEventDecoded> => {
const decoded = web3.eth.abi.decodeLog(
conversionEventAbi,
rawEvent.data,
rawEvent.topics
);
const blockNumber = String(web3.utils.toDecimal(rawEvent.blockNumber));
const txHash = rawEvent.transactionHash;
const [, fromAddress, toAddress, trader] = rawEvent.topics;
const picked = pick(
decoded,
conversionEventNetworkAbi.map(abi => abi.name)
) as unknown as {
fromAmount: string;
toAmount: string;
conversionFee: string;
};
const res = {
blockNumber,
txHash,
id: txHash,
data: {
from: {
address: removeLeadingZeros(fromAddress),
weiAmount: picked.fromAmount
},
to: {
address: removeLeadingZeros(toAddress),
weiAmount: picked.toAmount
},
trader: removeLeadingZeros(trader)
}
};
return res;
}
Example #26
Source File: Items.tsx From yforms with MIT License | 5 votes |
Items = (props: YFormItemsProps) => {
const formProps = useContext(YForm.YFormContext);
const { getScene } = formProps;
const itemsProps = useContext(YForm.YFormItemsContext);
const mergeProps = merge(
{},
pick(formProps, ['scenes', 'offset', 'disabled']),
itemsProps,
props,
);
const { scenes: thisScenes } = mergeProps;
const _defaultData = { formProps, itemsProps: props };
mapKeys(thisScenes, (value: boolean, key: string) => {
if (value && getScene[key] && getScene[key].items) {
const data = getScene[key].items(_defaultData);
if (data) {
_defaultData.itemsProps = { ..._defaultData.itemsProps, ...data.itemsProps };
}
}
});
const _props = mergeWithDom({}, mergeProps, _defaultData.itemsProps, {
offset: (props.offset || 0) + (itemsProps.offset || 0),
});
const { isShow, className, style, children, noStyle, shouldUpdate } = _props;
const itemList = [];
const eachItem = (
list: YFormItemProps['children'][] | React.ReactFragment[],
pIndex?: number,
) => {
if (isArray(list)) {
forEach(list, (item, index) => {
// 如果还是是数组就回调该方法
// if (isArray(item)) return eachItem(item, index);
if (isArray(item)) {
return eachItem(item, index);
}
const _index = pIndex ? `${pIndex}_${index}` : index;
// 如果是 dom 直接渲染
if (isValidElement(item)) {
return itemList.push(item);
}
// 如果不是对象直接渲染
if (!isObject(item)) {
return itemList.push(item);
}
return itemList.push(<YForm.Item {...item} key={_index} />);
});
}
};
// 遍历元素
eachItem(isArray(children) ? children : [children]);
const child = (
<YForm.YFormItemsContext.Provider value={pick(_props, ['scenes', 'offset', 'disabled'])}>
{itemList}
</YForm.YFormItemsContext.Provider>
);
const dom = noStyle ? (
child
) : (
<div className={classNames('yform-items', className)} style={style}>
{child}
</div>
);
if (typeof isShow === 'function') {
return (
<Form.Item noStyle shouldUpdate={shouldUpdate}>
{(form) => isShow(form.getFieldsValue(true)) && dom}
</Form.Item>
);
}
if ('isShow' in props && !props.isShow) return null;
return dom;
}
Example #27
Source File: index.tsx From next-basics with GNU General Public License v3.0 | 5 votes |
private initData(mutableProps: { modalTitle: string }): void {
const pickFields = pick(this.fields, ["modalTitle"]);
forEach(pickFields, (fieldKey, field: string) => {
set(mutableProps, field, get(this.dataSource, fieldKey));
});
}
Example #28
Source File: build.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
extractData = (data: any) => pick(data, ['source', 'branch', 'ymlName', 'workspace'])
Example #29
Source File: index.tsx From gant-design with MIT License | 5 votes |
ModalComponent = (modelProps: ModalProps) => {
const globalConfig = getGlobalConfig();
const props = { ...globalConfig, ...modelProps };
const {
id = uuid,
throttle = 0,
children,
maxZIndex = 999,
isModalDialog = true,
onSizeChange,
type = 'resize',
...restProps
} = props;
const { itemState = {}, width: restWidth } = restProps;
const { width: itemWidth, height: itemHeight } = itemState;
//兼容type为autoHeight的情况中的指定高度
//宽度
let modelWidth: number | string;
if (typeof itemWidth === 'number') {
modelWidth = itemWidth;
}
if (typeof itemWidth === 'string' && itemWidth.indexOf('%')) {
modelWidth = (window.innerWidth * parseInt(itemWidth)) / 100;
}
if (restWidth) {
modelWidth = restWidth;
}
//高度
let modelHeight: number;
if (typeof itemHeight === 'number') {
modelHeight = itemHeight;
}
if (typeof itemHeight === 'string' && itemHeight.indexOf('%')) {
modelHeight = (window.innerHeight * parseInt(itemHeight)) / 100;
}
const contentHeight = useMemo(() => {
if (type === 'autoHeight') {
return 'auto';
}
if (itemHeight && modelHeight) {
return modelHeight - 0;
}
}, [type, itemHeight, modelHeight]);
return (
<>
{type === 'resize' ? (
<ResizableProvider maxZIndex={maxZIndex} {...pick(restProps, providerPropKeys)}>
<ResizableModal
id={id}
isModalDialog={isModalDialog}
{...omit(restProps, providerPropKeys)}
>
<ContextContent
id={id}
children={children}
throttleTime={throttle}
onSizeChange={onSizeChange}
/>
</ResizableModal>
</ResizableProvider>
) : (
<Modal width={modelWidth} {...restProps}>
<div
style={{
height: contentHeight,
}}
>
{children}
</div>
</Modal>
)}
</>
);
}