lodash#find TypeScript 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: utils.ts From yforms with MIT License | 7 votes |
onFormatFieldsValue = (formatFieldsValue: FormatFieldsValue[]) => {
return (list: FormatFieldsValue[]) => {
const _formatFields = formatFieldsValue;
forEach(list, (item) => {
// 已存在不再注册
if (!find(_formatFields, { name: item.name })) {
_formatFields.push(item);
}
});
return _formatFields;
};
}
Example #2
Source File: utils.tsx From erda-ui with GNU Affero General Public License v3.0 | 7 votes |
findTargetNode = (nodeKey: string, nodeTree: TreeNode[]): null | TreeNode => {
if (nodeTree && nodeTree.length > 0) {
let target = find(nodeTree, { key: nodeKey }) || null;
if (!target) {
let i = 0;
while (!target && i < nodeTree.length) {
const { children } = nodeTree[i];
if (children) {
target = findTargetNode(nodeKey, children);
}
i += 1;
}
}
return target;
}
return null;
}
Example #3
Source File: Read.tsx From sc2-planner with MIT License | 6 votes |
speak(
events: string,
when = 0,
isLastMessage = false,
language = "Google UK English Female"
): void {
if (this.synth.speaking) {
this.stop()
}
this.lineHandlers.push(
setTimeout(() => {
const utterThis = new SpeechSynthesisUtterance(events)
if (utterThis) {
if (!this.voices.length) {
// Insist on initializing this.voices, sometimes it doesn't work straight away
this.voices = this.synth.getVoices()
}
const voice = find(this.voices, { name: language })
if (voice) {
utterThis.voice = voice
}
this.synth.speak(utterThis)
if (isLastMessage) {
this.lineHandlers = []
this.setState({
canStop: false,
})
}
}
}, when)
)
}
Example #4
Source File: is-element-sub-class.ts From ui5-language-assistant with Apache License 2.0 | 6 votes |
function isSubClass(
superClassFqn: string,
clazz: UI5Class | undefined
): clazz is UI5Class {
if (clazz === undefined) {
return false;
}
const superClasses = getSuperClasses(clazz);
return (
find(superClasses, (_) => ui5NodeToFQN(_) === superClassFqn) !== undefined
);
}
Example #5
Source File: dcs_util.ts From project-tauntaun with GNU Lesser General Public License v3.0 | 6 votes |
export function findGroupById(mission: Mission, groupId: number): Group | undefined {
for (const groupArray of getGroupArrays(mission)) {
const group = groupArray.find(g => g.group.id === groupId);
if (group) return group.group;
}
return undefined;
}
Example #6
Source File: electron.service.ts From WowUp with GNU General Public License v3.0 | 6 votes |
public async getAppOptions(): Promise<AppOptions> {
if (!this._opts) {
console.debug("getAppOptions");
// TODO check protocols here
const launchArgs = await this.invoke<string[]>(IPC_GET_LAUNCH_ARGS);
this._opts = (<any>minimist(launchArgs.slice(1), {
boolean: ["hidden", "quit"],
string: ["install"],
})) as AppOptions;
// Find the first protocol arg if any exist
const customProtocol = find(launchArgs, (arg) => isProtocol(arg));
if (customProtocol) {
// If we did get a custom protocol notify the app
this._customProtocolSrc.next(customProtocol);
}
}
return this._opts;
}
Example #7
Source File: issue-372-spec.ts From S2 with MIT License | 6 votes |
describe('GrandTotal Cells Rendering Test', () => {
let s2: PivotSheet;
beforeEach(() => {
s2 = new PivotSheet(getContainer(), mockDataConfig, s2Options);
s2.render();
});
test('should get right height of GrandTotal node', () => {
const hierarchy = s2.facet.layoutResult.colsHierarchy;
const grandTotalNode = find(
hierarchy.getNodes(0),
(node: Node) => node.isGrandTotals,
) as Node;
expect(grandTotalNode.height).toEqual(30);
});
});
Example #8
Source File: addressesDbService.ts From nautilus-wallet with MIT License | 6 votes |
public async bulkPut(addresses: IDbAddress[], walletId: number): Promise<void> {
const dbAddresses = await this.getByWalletId(walletId);
const putAddresses: IDbAddress[] = [];
for (const address of addresses) {
const dbAddress = find(dbAddresses, (a) => a.script == address.script);
if (this.isNewOrModified(address, dbAddress)) {
address.walletId = walletId;
putAddresses.push(address);
}
}
if (putAddresses.length > 0) {
await dbContext.addresses.bulkPut(putAddresses);
}
}
Example #9
Source File: VerdictFilterDropdown.tsx From hubble-ui with Apache License 2.0 | 6 votes |
VerdictFilterDropdown = memo<Props>(function VerdictFilterDropdown(
props,
) {
const popover = usePopover();
const getLabel = useCallback(() => {
const found = find(filters, f => f.verdict === props.verdict);
return found ? found.title : '';
}, [props.verdict]);
const content = (
<Menu>
{filters.map(filter => (
<MenuItem
key={String(filter.verdict)}
active={props.verdict == filter.verdict}
text={filter.title}
onClick={() => props.onSelect?.(filter.verdict)}
/>
))}
</Menu>
);
return (
<Popover {...popover.props} content={content}>
<FilterIcon
icon={<VerdictIcon />}
text={getLabel()}
onClick={popover.toggle}
className={classnames({
[css.verdictFilterDropped]: props.verdict === Verdict.Dropped,
[css.verdictFilterForwarded]: props.verdict === Verdict.Forwarded,
})}
/>
</Popover>
);
})
Example #10
Source File: index.tsx From next-basics with GNU General Public License v3.0 | 6 votes |
connectedCallback(): void {
if (!isEmpty(this.hotkeysConfig)) {
hotkeys.filter = function (event) {
return true;
};
hotkeys(map(this.hotkeysConfig, "key").join(","), (event, handler) => {
event.preventDefault();
const found = find(this.hotkeysConfig, ["key", handler.key]);
if (found?.eventName) {
if (!this.disabled) {
this.dispatchEvent(new CustomEvent(found.eventName));
}
}
});
}
}
Example #11
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 6 votes |
getValueByOptions = (options: IOption[], value: IOption[]) => {
const reValue = [] as IOption[];
map(value, (vItem) => {
if (reValue.length === 0) {
reValue.push(find(options, { value: vItem.value }) as IOption);
} else {
const lastVal = last(reValue) as IOption;
lastVal && reValue.push(find(lastVal.children, { value: vItem.value }) as IOption);
}
});
return compact(reValue);
}
Example #12
Source File: gamelogic.ts From sc2-planner with MIT License | 5 votes |
static addItemToBO(
prevGamelogic: GameLogic,
item: IBuildOrderElement,
insertIndex: number
): [GameLogic, number] {
const bo = prevGamelogic.bo
const initialBOLength = bo.length
if (item.type === "upgrade" && prevGamelogic.upgrades.has(item.name)) {
// upgrade already researched, don't do anything.
return [prevGamelogic, insertIndex]
}
bo.splice(insertIndex, 0, item)
// Re-calculate build order
// // Caching using snapshots - idk why this isnt working properly
// const latestSnapshot = gamelogic.getLastSnapshot()
// if (latestSnapshot) {
// gamelogic.loadFromSnapshotObject(latestSnapshot)
// }
// gamelogic.bo = cloneDeep(bo)
// gamelogic.runUntilEnd()
// Non cached:
// Fill up with missing items
let gamelogic = GameLogic.simulatedBuildOrder(prevGamelogic, bo)
let fillingLoop = 0
// Add required items if need be
if (insertIndex === bo.length - 1 && !prevGamelogic.errorMessage) {
do {
if (fillingLoop > 0) {
// Simulation is done already, the first time
gamelogic = GameLogic.simulatedBuildOrder(prevGamelogic, bo)
}
if (gamelogic.errorMessage && gamelogic.requirements) {
fillingLoop++
const duplicatesToRemove: IBuildOrderElement[] = []
for (const req of gamelogic.requirements) {
let duplicateItem: IBuildOrderElement | undefined
if (!gamelogic.canRequirementBeDuplicated(req.name, item.name)) {
duplicateItem = find(bo, req)
}
// Add item if absent, or present later in the bo
if (!duplicateItem || bo.indexOf(duplicateItem) >= insertIndex) {
bo.splice(insertIndex, 0, req)
if (duplicateItem) {
duplicatesToRemove.push(duplicateItem)
}
}
}
for (const duplicate of duplicatesToRemove) {
remove(bo, (item) => item === duplicate) // Specificaly remove the later one
}
}
} while (gamelogic.errorMessage && gamelogic.requirements && fillingLoop < 25)
}
const insertedItems = bo.length - initialBOLength
return [gamelogic, insertedItems]
}
Example #13
Source File: index.ts From barista with Apache License 2.0 | 5 votes |
export function getDefaultValue(elements: Array<ILookupModel>, code: string = null) {
let result = null;
if (code) {
result = find(elements, { code });
}
return result || find(elements, { isDefault: true });
}
Example #14
Source File: completion-items.ts From ui5-language-assistant with Apache License 2.0 | 5 votes |
function getClassNamespacePrefix(
suggestion: UI5ClassesInXMLTagNameCompletion,
additionalTextEdits: TextEdit[]
): string | undefined {
const xmlElement = suggestion.astNode;
const parent = suggestion.ui5Node.parent;
/* istanbul ignore else */
if (parent !== undefined) {
const parentFQN = ui5NodeToFQN(parent);
let xmlnsPrefix = findKey(xmlElement.namespaces, (_) => _ === parentFQN);
// Namespace not defined in imports - guess it
if (xmlnsPrefix === undefined) {
// It should be the parent simple name by default, but if that already exists we'll add an index to it (name2 etc)
xmlnsPrefix = parent.name;
let i = 2;
while (
find(xmlElement.namespaces, (v, k) => k === xmlnsPrefix) !== undefined
) {
xmlnsPrefix = parent.name + i;
++i;
}
const addNamespaceEdit = getAddNamespaceEdit(
xmlElement,
xmlnsPrefix,
parentFQN
);
// Add text edit for the missing xmlns attribute definition
// The 'else' should not happen because it would only happen in case we can't find the root element of
// the document, and in that case we also won't get any suggestions for classes
/* istanbul ignore else */
if (addNamespaceEdit !== undefined) {
additionalTextEdits.push(addNamespaceEdit);
}
}
if (
xmlnsPrefix !== undefined &&
xmlnsPrefix !== DEFAULT_NS &&
xmlnsPrefix.length > 0
) {
return xmlnsPrefix;
}
}
return undefined;
}
Example #15
Source File: issue-836-spec.ts From S2 with MIT License | 5 votes |
describe('GrandTotal and SubTotal Cells Rendering Test', () => {
let s2: PivotSheet;
beforeEach(() => {
s2 = new PivotSheet(getContainer(), mockDataConfig, s2Options);
s2.render();
});
test('should get the right height of GrandTotal node', () => {
const hierarchy = s2.facet.layoutResult.colsHierarchy;
const grandTotalNode = find(
hierarchy.getNodes(0),
(node: Node) => node.isGrandTotals,
) as Node;
expect(grandTotalNode.height).toEqual(60);
});
test('should get the right position of GrandTotal Measure node', () => {
const hierarchy = s2.facet.layoutResult.colsHierarchy;
const grandTotalNode = find(
hierarchy.getNodes(0),
(node: Node) => node.isGrandTotals,
) as Node;
expect(grandTotalNode.children[0].y).toEqual(60);
expect(grandTotalNode.children[0].x).toEqual(0);
});
test('should get the right height of SubTotal node', () => {
const hierarchy = s2.facet.layoutResult.colsHierarchy;
const subTotalNode = find(
hierarchy.getNodes(1),
(node: Node) => node.isSubTotals,
) as Node;
expect(subTotalNode.height).toEqual(30);
});
test('should get the right position of subTotalNode Measure node', () => {
const hierarchy = s2.facet.layoutResult.colsHierarchy;
const subTotalNode = find(
hierarchy.getNodes(1),
(node: Node) => node.isSubTotals,
) as Node;
expect(subTotalNode.children[0].y).toEqual(60);
expect(subTotalNode.children[0].x).toEqual(192);
});
});
Example #16
Source File: extension-registry.tsx From XFlow with MIT License | 5 votes |
getExtension = (config_type: string) => {
return find(this.extensions, extension => get(extension, 'config.CONFIG_TYPE') === config_type)
}
Example #17
Source File: team.ts From fishbowl with MIT License | 5 votes |
export function currentPlayerTeam(
currentPlayerId: Player["id"],
players: Players
): Team {
return find(players, (player) => player.id === currentPlayerId)?.team as Team
}
Example #18
Source File: ergoApiHandlers.ts From nautilus-wallet with MIT License | 5 votes |
export async function handleGetBoxesRequest(
request: RpcMessage,
port: chrome.runtime.Port,
session?: Session
) {
if (!validateRequest(session, request, port)) {
return;
}
let tokenId = ERG_TOKEN_ID;
let amount = new BigNumber(0);
if (request.params) {
tokenId = request.params[1] as string;
if (!tokenId || tokenId === "ERG") {
tokenId = ERG_TOKEN_ID;
}
let error: APIError | undefined = undefined;
if (request.params[0]) {
amount = toBigNumber(request.params[0]) || new BigNumber(0);
}
if (request.params[2]) {
error = {
code: APIErrorCode.InvalidRequest,
info: "pagination is not implemented"
};
}
if (error) {
postErrorMessage(error, request, port);
}
}
let selected = await fetchBoxes(session!.walletId!);
if (tokenId != ERG_TOKEN_ID) {
selected = selected.filter((box) => findIndex(box.assets, (a) => a.tokenId === tokenId) > -1);
}
if (!amount.isZero()) {
let acc = new BigNumber(0);
if (tokenId === ERG_TOKEN_ID) {
selected = selected.filter((box) => {
if (acc.isGreaterThanOrEqualTo(amount)) {
return false;
}
acc = acc.plus(toBigNumber(box.value)!);
return true;
});
} else {
selected = selected.filter((box) => {
if (acc.isGreaterThanOrEqualTo(amount)) {
return false;
}
acc = acc.plus(toBigNumber(find(box.assets, (a) => a.tokenId === tokenId)?.amount ?? 0)!);
return true;
});
}
}
postConnectorResponse(
{
isSuccess: true,
data: selected
},
request,
port
);
}
Example #19
Source File: index.tsx From next-basics with GNU General Public License v3.0 | 5 votes |
connectedCallback(): void {
this.style.display = "inline-block";
this.addEventListener("click", (e) => {
const foundOperatingArea = find(
e.composedPath(),
(element: HTMLElement) => {
return (
element.classList &&
element.classList.value.includes("operateContainer")
);
}
) as HTMLElement;
if (foundOperatingArea) {
return;
}
const disabledField = get(this.fields, "disabled");
const disabled =
this.disabled ||
(disabledField ? get(this.dataSource, disabledField) : false);
if (disabled) {
return;
}
const foundCardListContainerArea = find(
e.composedPath(),
(element: HTMLElement) => {
return (
element.classList && element.classList.value.includes("cardItem")
);
}
) as HTMLElement;
// Todo(lynette): shadow dom中link的跳转会刷新整个页面,所以先这样处理。Issue:https://github.com/facebook/react/issues/9242
if (foundCardListContainerArea) {
this._handleClick();
if (this.href) {
const a = document.createElement("a");
a.href = this.href;
if (this.target && this.target !== "_self") {
window.open(this.href, this.target);
} else {
a.click();
}
} else {
const url =
this.url ||
(this.urlTemplate &&
parseTemplate(this.urlTemplate, this.dataSource));
if (url) {
const history = getHistory();
if (this.target && this.target !== "_self") {
window.open(url, this.target);
} else {
history.push(url);
}
}
}
}
});
this._render();
}
Example #20
Source File: youtube-captions-scraper.tsx From obsidian-annotator with GNU Affero General Public License v3.0 | 5 votes |
export async function getSubtitles(
fetch: FetchType,
{
videoID,
lang = 'en'
}: {
videoID: string;
lang: 'en' | 'de' | 'fr' | void;
}
) {
const data = await (await fetch(`https://youtube.com/watch?v=${videoID}`)).text();
// * ensure we have access to captions data
if (!data.includes('captionTracks')) throw new Error(`Could not find captions for video: ${videoID}`);
const regex = /({"captionTracks":.*isTranslatable":(true|false)}])/;
const [match] = regex.exec(data);
const { captionTracks } = JSON.parse(`${match}}`);
const subtitle =
find(captionTracks, {
vssId: `.${lang}`
}) ||
find(captionTracks, {
vssId: `a.${lang}`
}) ||
find(captionTracks, ({ vssId }) => vssId && vssId.match(`.${lang}`));
// * ensure we have found the correct subtitle lang
if (!subtitle || (subtitle && !subtitle.baseUrl)) throw new Error(`Could not find ${lang} captions for ${videoID}`);
const transcript = await (await fetch(subtitle.baseUrl)).text();
const lines = transcript
.replace('<?xml version="1.0" encoding="utf-8" ?><transcript>', '')
.replace('</transcript>', '')
.split('</text>')
.filter(line => line && line.trim())
.map(line => {
const startRegex = /start="([\d.]+)"/;
const durRegex = /dur="([\d.]+)"/;
const [, start] = startRegex.exec(line);
const [, dur] = durRegex.exec(line);
const htmlText = line
.replace(/<text.+>/, '')
.replace(/&/gi, '&')
.replace(/<\/?[^>]+(>|$)/g, '');
const decodedText = he.decode(htmlText);
const text = striptags(decodedText);
return {
start,
dur,
text
};
});
return lines;
}
Example #21
Source File: index.tsx From erda-ui with GNU Affero General Public License v3.0 | 5 votes |
handleItemChange = (e: React.ChangeEvent<HTMLInputElement>, name: string, uniKey: string) => {
const { value } = e.target;
const dataSource = [...this.state.dataSource];
const { onChange } = this.props;
(find(dataSource, { uniKey }) as object)[name] = value;
this.setState({ dataSource });
onChange && onChange(Array.isArray(this.props.data) ? dataSource : convertToMapData(dataSource));
};