lodash#mean TypeScript Examples
The following examples show how to use
lodash#mean.
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: analysis-utils.ts From prism-frontend with MIT License | 7 votes |
operations = {
min: (data: number[]) => min(data),
max: (data: number[]) => max(data),
sum, // sum method directly from lodash
mean, // mean method directly from lodash
median: (data: number[]) => {
// eslint-disable-next-line fp/no-mutating-methods
const sortedValues = [...data].sort();
// Odd cases we use the middle value
if (sortedValues.length % 2 !== 0) {
return sortedValues[Math.floor(sortedValues.length / 2)];
}
// Even cases we average the two middles
const floor = sortedValues.length / 2 - 1;
const ceil = sortedValues.length / 2;
return (sortedValues[floor] + sortedValues[ceil]) / 2;
},
}
Example #2
Source File: map.ts From aqualink-app with MIT License | 6 votes |
getMiddlePoint = (point: Point | Polygon): Position => {
if (point.type === "Point") {
return point.coordinates;
}
const coordArray = point.coordinates[0];
const lngArray = coordArray.map((item) => item[0]);
const latArray = coordArray.map((item) => item[1]);
const lngMean = mean(lngArray);
const latMean = mean(latArray);
return [lngMean, latMean];
}
Example #3
Source File: GoCdBuildsInsights.tsx From backstage with Apache License 2.0 | 6 votes |
function formatMean(durations: Duration[]): string {
if (durations.length === 0) {
return 'N/A';
}
const mttr: Duration = Duration.fromMillis(
mean(durations.map(i => i.milliseconds)),
);
return mttr.toFormat("d'd' h'h' m'm' s's'");
}
Example #4
Source File: today.tsx From office-hours with GNU General Public License v3.0 | 5 votes |
collapseHeatmap = (heatmap: Heatmap): Heatmap =>
chunk(heatmap, 4).map((hours) => {
const filteredOfficeHours = hours.filter((v) => v !== -1);
return filteredOfficeHours.length > 0 ? mean(filteredOfficeHours) : -1;
})
Example #5
Source File: PopularTimes.tsx From office-hours with GNU General Public License v3.0 | 4 votes |
export default function PopularTimes({ heatmap }: HeatmapProps): ReactElement {
const [currentDayOfWeek, setCurrentDayOfWeek] = useState(new Date().getDay());
const [firstHour, lastHour] = findWeekMinAndMax(heatmap);
const dailyAvgWaitTimes: number[] = chunk(heatmap, 24).map((hours) => {
const filteredOfficeHours = hours.filter((v) => v !== -1);
return filteredOfficeHours.length > 0 ? mean(filteredOfficeHours) : -1;
});
return (
<div className="hide-in-percy">
<TitleRow>
<h2>Wait Times on</h2>
<Dropdown
trigger={["click"]}
overlay={
<Menu>
{DAYS_OF_WEEK.map((dayName, i) => (
<Menu.Item key={dayName}>
<a onClick={() => setCurrentDayOfWeek(i)}>{dayName}</a>
</Menu.Item>
))}
</Menu>
}
>
<WeekdayDropdown>
{DAYS_OF_WEEK[currentDayOfWeek]}
<DownOutlined />
</WeekdayDropdown>
</Dropdown>
</TitleRow>
<GraphWithArrow>
<GraphArrowButtons
onClick={() => setCurrentDayOfWeek((7 + currentDayOfWeek - 1) % 7)}
>
<LeftOutlined />
</GraphArrowButtons>
<GraphContainer>
<ParentSize>
{({ width }) => (
<TimeGraph
values={heatmap
.slice(currentDayOfWeek * 24, (currentDayOfWeek + 1) * 24 - 1)
.map((i) => (i < 0 ? 0 : Math.floor(i)))}
maxTime={Math.max(...heatmap)}
firstHour={firstHour}
lastHour={lastHour}
width={width}
height={220}
/>
)}
</ParentSize>
</GraphContainer>
<GraphArrowButtons
onClick={() => setCurrentDayOfWeek((currentDayOfWeek + 1) % 7)}
>
<RightOutlined />
</GraphArrowButtons>
</GraphWithArrow>
{dailyAvgWaitTimes[currentDayOfWeek] >= 0 && (
<GraphNotes>
<ClockCircleOutlined /> {DAYS_OF_WEEK[currentDayOfWeek]}s have{" "}
<strong>
{generateBusyText(currentDayOfWeek, dailyAvgWaitTimes)}
</strong>{" "}
wait times.
</GraphNotes>
)}
{new Date().getDay() === currentDayOfWeek &&
heatmap[currentDayOfWeek * 24 + new Date().getHours()] >= 0 && (
<GraphNotes>
<HourglassOutlined /> At {formatDateHour(new Date().getHours())},
people generally wait{" "}
<strong>
{formatWaitTime(
heatmap[currentDayOfWeek * 24 + new Date().getHours()]
)}
</strong>
.
</GraphNotes>
)}
</div>
);
}
Example #6
Source File: heatmap.service.ts From office-hours with GNU General Public License v3.0 | 4 votes |
// PRIVATE function that is public for testing purposes
// Rewind through the last few weeks and for each time interval,
// figure out how long wait time would have been if you had joined the queue at that time
// Timezone should be IANA
// Returns heatmap in the timezone (ie 3rd bucket is 3am in that timezone)
_generateHeatMapWithReplay(
questions: QuestionModel[],
hourTimestamps: [number, number][],
timezone: string,
bucketSize: number,
samplesPerBucket: number,
): Heatmap {
const sampleInterval = bucketSize / samplesPerBucket;
/*
TEST: Question1 is 3:05 - 3:25
// The next question is 3:21 - 3:49
THe following question is 4:05 - 4:10
Bucket = 60, Samples = 3, so timepoints are: 3:00, 3:20, 3:40.
3:20 sample gets waittime of 5 minutes
3:40 samples get waittimes of 9 minutes
4:00 sample gets waittime of 0 minutes
If i entered the queue at that time when should I have gotten help?
Every interval of minutes for the past 5 weeks are aggregated (by taking the avg)
analyze the buckets to find the closest time approximation
look at question Q1 and the next question Q2
for all sample timepoints between Q1.createdAt and Q2.createdAt:
- sample = Q1.helpedAt - timepoint (if negative, then it's 0)
*/
function dateToBucket(date: Date | number): number {
// parse in zone to handle daylight savings by getting day/hour/minute within that IANA zone
const cInZone = moment.tz(date, timezone);
return Math.floor(
(cInZone.day() * 24 * 60 + cInZone.hour() * 60 + cInZone.minute()) /
bucketSize,
);
}
const timepointBuckets: number[][] = [
...Array((24 * 7 * 60) / bucketSize),
].map(() => []);
if (questions.length) {
const startDate = questions[0].createdAt;
const sunday = moment.tz(startDate, timezone).startOf('week').toDate();
function getNextTimepointIndex(date: Date): number {
return Math.floor(timeDiffInMins(date, sunday) / sampleInterval) + 1;
}
// Get the date of the sample timepoint immediately after the given date
function getNextSampleTimepoint(date: Date): Date {
const timepointIndex = getNextTimepointIndex(date);
return new Date(
sunday.getTime() + timepointIndex * sampleInterval * 60 * 1000,
);
}
// Get all timepoints between the two dates
function getSampleTimepointsInDateRange(
date1: Date,
date2: Date,
): Date[] {
const ret = [];
let curr = getNextSampleTimepoint(date1);
while (curr.getTime() < date2.getTime()) {
ret.push(curr);
curr = getNextSampleTimepoint(curr);
}
return ret;
}
// Get the start time of the current bucket
function lastBucketBoundary(date: Date): moment.Moment {
const startOfWeek = moment.tz(date, timezone).startOf('week');
const m = moment(date);
return m.subtract(m.diff(startOfWeek, 'm') % bucketSize, 'm');
}
// go two questions at a time
let isFirst = true;
for (let i = 0; i < questions.length; i++) {
const curr = questions[i];
const next = questions[i + 1];
const isLast = i === questions.length - 1;
// get the timepoints in between
let sampledTimepoints = getSampleTimepointsInDateRange(
isFirst
? lastBucketBoundary(curr.createdAt)
.subtract(1, 's') // so that we get the first timepoint
.toDate()
: curr.createdAt,
isLast
? lastBucketBoundary(curr.helpedAt)
.add(bucketSize, 'm') // to get the nextBucketBoundary
.toDate()
: next.createdAt,
);
sampledTimepoints = sampledTimepoints.filter((time) =>
hourTimestamps.some(([start, end]) =>
inRange(time.getTime(), start, end),
),
);
// Pad the first bucket with zeros to account for timepoints before the first
if (sampledTimepoints.length > 0 && isFirst) {
isFirst = false;
}
// When we would have hypothetically gotten help at this timepoint
for (const c of sampledTimepoints) {
let wait = 0;
if (
inRange(
c.getTime(),
curr.createdAt.getTime(),
curr.helpedAt.getTime(),
)
) {
wait = (curr.helpedAt.getTime() - c.getTime()) / 60000;
}
const bucketIndex = dateToBucket(c);
timepointBuckets[bucketIndex].push(wait);
}
}
}
// Were there ever office hours in this bucket?
const wereHoursDuringBucket: boolean[] = [
...Array((24 * 7 * 60) / bucketSize),
];
for (const [start, end] of hourTimestamps) {
//prevents an office hour from [N, M] to register in multiple buckets
for (const i of range(dateToBucket(start), dateToBucket(end - 1) + 1)) {
wereHoursDuringBucket[i] = true;
}
}
const h: Heatmap = timepointBuckets.map((samples, i) => {
if (samples.length > 0) {
return mean(samples);
} else if (wereHoursDuringBucket[i]) {
return 0;
} else {
return -1;
}
});
return h;
}
Example #7
Source File: AccordionReport.tsx From yearn-watch-legacy with GNU Affero General Public License v3.0 | 4 votes |
AccordionReport = (props: AccordionReportProps) => {
const { data, tokenDecimals, network } = props;
const aprList = compact(data.map((item) => item.results?.apr));
const averageApr = aprList.length === 0 ? 0 : mean(aprList);
const medianApr = aprList.length === 0 ? 0 : median(aprList);
const averageAprLabel = `Average APR: ${averageApr.toFixed(2)}%`;
const medianAprLabel = `Median APR: ${medianApr.toFixed(2)}%`;
const topLabel =
data.length === 0
? 'No Reports Loaded'
: `Last ${data.length} reports.`;
return (
<div>
<Container>
<Grid container spacing={3} style={{ marginTop: 10 }}>
<Grid item xs={4}>
<StyledTypography>{topLabel}</StyledTypography>
</Grid>
<Grid item xs={4}>
<StyledTypography>{averageAprLabel}</StyledTypography>
</Grid>
<Grid item xs={4}>
<StyledTypography>{medianAprLabel}</StyledTypography>
</Grid>
</Grid>
{data.map((res: StrategyReport, index: number) => {
return (
<StyledAccordion key={index}>
<AccordionSummary
expandIcon={<StyledExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<EtherScanLink
transactionHash={res.transactionHash}
network={network}
/>
<StyledSubTypography>
Timestamp:
<br />
{unixMsToIsoString(res.timestamp)}
</StyledSubTypography>
</AccordionSummary>
<AccordionDetails>
<Grid container spacing={1}>
<Grid container spacing={1}>
<ItemDescription
label="Debt Added"
value={displayAmount(
res.debtAdded,
tokenDecimals
)}
md={3}
/>
<ItemDescription
label="Debt Limit"
value={displayAmount(
res.debtLimit,
tokenDecimals
)}
md={3}
/>
<ItemDescription
label="Debt Paid"
value={displayAmount(
res.debtPaid,
tokenDecimals
)}
md={3}
/>
<ItemDescription
label="Total Debt"
value={displayAmount(
res.totalDebt,
tokenDecimals
)}
md={3}
/>
</Grid>
<Grid container spacing={1}>
<ItemDescription
label="Profit"
value={displayAmount(
res.profit,
tokenDecimals
)}
md={3}
/>
<ItemDescription
label="Total Profit"
value={displayAmount(
res.totalProfit,
tokenDecimals
)}
md={3}
/>
<ItemDescription
label="Loss"
value={displayAmount(
res.loss,
tokenDecimals
)}
md={3}
/>
<ItemDescription
label="Total Loss"
value={displayAmount(
res.totalLoss,
tokenDecimals
)}
md={3}
/>
</Grid>
<Grid container spacing={1}>
<ItemDescription
label="Duration (hours)"
value={msToHours(
res.results
? res.results.duration
: 0
).toFixed(2)}
visible={res.results !== undefined}
md={3}
helpTitle="What is it?"
helpDescription={
<Fragment>
The duration is the time
elapsed between this report
and the previous.
</Fragment>
}
/>
<ItemDescription
label="Duration PR"
value={`${res.results?.durationPr.toFixed(
6
)} %`}
visible={res.results !== undefined}
md={3}
helpTitle="What is the duration PR?"
helpDescription={
<Fragment>
It is the percentage rate
for the given duration
period:
<pre>
{
'profit = current.totalGain - previous.totalGain'
}
</pre>
<pre>
{
'durationPR = profit / current.totalDebt'
}
</pre>
</Fragment>
}
/>
<ItemDescription
label="APR"
value={`${res.results?.apr.toFixed(
2
)} %`}
visible={res.results !== undefined}
md={3}
helpTitle="How is APR calculated?"
helpDescription={
<Fragment>
It compares the current and
previous reports applying
this formula:
<pre>
{
'profit = current.totalGain - previous.totalGain'
}
</pre>
<pre>
{
'timeBetweenReports (days) = (current.timestamp - previous.timestamp ) * millisecondsPerDay'
}
</pre>
<pre>
{
'yearOverDuration = daysPerYear (365) / timeBetweenReports'
}
</pre>
<pre>
{
'profitOverTotalDebt = profit / current.totalDebt'
}
</pre>
<pre>
{
'APR = profitOverTotalDebt * yearOverDuration'
}
</pre>
</Fragment>
}
/>
</Grid>
</Grid>
</AccordionDetails>
</StyledAccordion>
);
})}
</Container>
</div>
);
}
Example #8
Source File: index.tsx From yearn-watch-legacy with GNU Affero General Public License v3.0 | 4 votes |
_StrategiesList = (props: StrategiesListProps) => {
const { vault, network, expand = true } = props;
const config = vault.configOK;
const [isReportsLoading, setIsReportsLoading] = useState(true);
const strategyReportContext = useStrategyReportContext();
useEffect(() => {
const loadStrategyReports = async () => {
try {
setIsReportsLoading(true);
const strategies = vault.strategies
? vault.strategies.map((s) => s.address)
: [];
getReportsForStrategies(
strategies,
network,
strategyReportContext
).then(() => {
setIsReportsLoading(false);
});
} catch (e: unknown) {
console.log('Error:', e);
setIsReportsLoading(false);
}
};
loadStrategyReports();
}, [vault.strategies]);
const displayAverageApr = (strategyId: string): string => {
const reports =
strategyReportContext.strategyReports[strategyId.toLowerCase()];
const aprList = compact(reports.map((item) => item.results?.apr));
const averageApr = aprList.length === 0 ? 0 : mean(aprList);
return `${averageApr.toFixed(2)}%`;
};
return (
<StyledDivRoot>
{vault.strategies &&
vault.strategies.map((strategy: Strategy, index: number) => (
<StyledMuiAccordion
config={config.toString()}
key={index}
defaultExpanded={expand}
style={{
border: shouldHighlightStrategy(strategy)
? '5px solid #ff6c6c'
: '',
}}
>
<AccordionSummary
expandIcon={<StyledExpandMoreIcon />}
aria-controls="panel1a-content"
id="panel1a-header"
>
<Grid container spacing={1}>
<Grid item md={12} xs={12}>
<Grid
container
spacing={1}
direction="row"
alignItems="center"
>
<Grid item md={1}></Grid>
<Grid item md={4} xs={12}>
<StyledTitle>
<CustomLink
to={`/network/${network}/vault/${strategy.vault}/strategy/${strategy.address}`}
>
<Hidden smUp>
{strategy.name.length >
20
? extractText(
strategy.name
)
: strategy.name}
</Hidden>
<Hidden smDown>
{strategy.name}
</Hidden>
<HealthCheckIcon
strategy={strategy}
/>
</CustomLink>
</StyledTitle>
</Grid>
<Hidden smDown>
<Grid item md={6} xs={9}>
<EtherScanLink
address={strategy.address}
network={network}
/>
</Grid>
</Hidden>
</Grid>
</Grid>
</Grid>
</AccordionSummary>
<Hidden smUp>
<Grid
container
spacing={1}
style={{ marginLeft: 10 }}
>
<Grid item md={8} xs={12}>
<EtherScanLink
address={strategy.address}
network={network}
/>
</Grid>
</Grid>
</Hidden>
<AccordionDetails>
<Grid container spacing={2}>
<Grid item md={12} xs={12}>
<Grid
container
spacing={1}
direction="row"
justifyContent="flex-start"
alignItems="center"
>
<Grid item md={1}></Grid>
<Grid item md={10} xs={12}>
<Grid container spacing={2}>
<Grid item md={12} xs={12}>
<Grid
container
spacing={1}
direction="row"
justifyContent="flex-start"
alignItems="center"
>
<Grid
item
xs={12}
md={3}
>
<StyledTitle>
{
strategy
.params
.lastReportText
}
</StyledTitle>
<StyledSubtitle>
Since Last
Report
</StyledSubtitle>
</Grid>
<StyleDiv />
<Grid
item
xs={12}
md={2}
>
<StyledTitle>
<DebTooltip
label={
vault &&
displayAmount(
strategy.params.totalDebt.toString(),
vault
.token
.decimals,
vault
.token
.decimals
)
}
/>
</StyledTitle>
<StyledSubtitle>
Total debt
</StyledSubtitle>
</Grid>
<StyleDiv />
<Grid
item
xs={12}
md={2}
>
<StyledTitle>
<DebTooltip
label={`${formatBPS(
strategy.params.debtRatio.toString()
)}%`}
/>
</StyledTitle>
<StyledSubtitle>
Debt ratio
</StyledSubtitle>
</Grid>
<StyleDiv />
<Grid
item
xs={12}
md={2}
>
<StyledTitle>
{isReportsLoading
? '--'
: displayAverageApr(
strategy.address
)}
</StyledTitle>
<StyledSubtitle>
Average APR
</StyledSubtitle>
</Grid>
<StyleDiv />
<Grid
item
xs={12}
md={2}
>
<StyledTitle>
<DebTooltip
label={
vault &&
displayAmount(
strategy.creditAvailable.toString(),
vault
.token
.decimals
)
}
/>
</StyledTitle>
<StyledSubtitle>
Credit available
</StyledSubtitle>
</Grid>
<StyleDiv />
<Grid
item
xs={12}
md={2}
>
<StyledTitle>
<DebTooltip
label={
vault &&
strategy.estimatedTotalAssets &&
displayAmount(
strategy.estimatedTotalAssets.toString(),
vault
.token
.decimals,
vault
.token
.decimals
)
}
/>
</StyledTitle>
<StyledSubtitle>
Total Estimated
Assets
</StyledSubtitle>
</Grid>
<StyleDiv />
<Grid
item
xs={12}
md={1}
>
<StyledTitleQueIndex
error={
strategy.withdrawalQueueIndex <
0
}
>
{vault &&
displayAmount(
strategy.withdrawalQueueIndex.toString(),
0
)}
</StyledTitleQueIndex>
<StyledSubtitleQueIndex
error={
strategy.withdrawalQueueIndex <
0
}
>
Index
</StyledSubtitleQueIndex>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
</Grid>
</AccordionDetails>
</StyledMuiAccordion>
))}
</StyledDivRoot>
);
}