Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: migrate to using arrow functions #2033

Merged
merged 1 commit into from
Nov 21, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/calculateRank.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
* @param {number} to The value to calculate the probability for.
* @returns {number} Probability.
*/
function normalcdf(mean, sigma, to) {
const normalcdf = (mean, sigma, to) => {
var z = (to - mean) / Math.sqrt(2 * sigma * sigma);
var t = 1 / (1 + 0.3275911 * Math.abs(z));
var a1 = 0.254829592;
Expand All @@ -24,7 +24,7 @@ function normalcdf(mean, sigma, to) {
sign = -1;
}
return (1 / 2) * (1 + sign * erf);
}
};

/**
* Calculates the users rank.
Expand All @@ -38,15 +38,15 @@ function normalcdf(mean, sigma, to) {
* @param {number} stargazers The number of stars.
* @returns {{level: string, score: number}}} The users rank.
*/
function calculateRank({
const calculateRank = ({
totalRepos,
totalCommits,
contributions,
followers,
prs,
issues,
stargazers,
}) {
}) => {
const COMMITS_OFFSET = 1.65;
const CONTRIBS_OFFSET = 1.65;
const ISSUES_OFFSET = 1;
Expand Down Expand Up @@ -98,7 +98,7 @@ function calculateRank({
})();

return { level, score: normalizedScore };
}
};

export { calculateRank };
export default calculateRank;
62 changes: 31 additions & 31 deletions src/common/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,64 +42,64 @@ const renderError = (message, secondaryMessage = "") => {
* @param {string} str String to encode.
* @returns {string} Encoded string.
*/
function encodeHTML(str) {
const encodeHTML = (str) => {
return str
.replace(/[\u00A0-\u9999<>&](?!#)/gim, (i) => {
return "&#" + i.charCodeAt(0) + ";";
})
.replace(/\u0008/gim, "");
}
};

/**
* Retrieves num with suffix k(thousands) precise to 1 decimal if greater than 999.
*
* @param {number} num The number to format.
* @returns {string|number} The formatted number.
*/
function kFormatter(num) {
const kFormatter = (num) => {
return Math.abs(num) > 999
? Math.sign(num) * parseFloat((Math.abs(num) / 1000).toFixed(1)) + "k"
: Math.sign(num) * Math.abs(num);
}
};

/**
* Checks if a string is a valid hex color.
*
* @param {string} hexColor String to check.
* @returns {boolean} True if the given string is a valid hex color.
*/
function isValidHexColor(hexColor) {
const isValidHexColor = (hexColor) => {
return new RegExp(
/^([A-Fa-f0-9]{8}|[A-Fa-f0-9]{6}|[A-Fa-f0-9]{3}|[A-Fa-f0-9]{4})$/,
).test(hexColor);
}
};

/**
* Returns boolean if value is either "true" or "false" else the value as it is.
*
* @param {string} value The value to parse.
* @returns {boolean | string} The parsed value.
*/
function parseBoolean(value) {
const parseBoolean = (value) => {
if (value === "true") {
return true;
} else if (value === "false") {
return false;
} else {
return value;
}
}
};

/**
* Parse string to array of strings.
*
* @param {string} str The string to parse.
* @returns {string[]} The array of strings.
*/
function parseArray(str) {
const parseArray = (str) => {
if (!str) return [];
return str.split(",");
}
};

/**
* Clamp the given number between the given range.
Expand All @@ -109,21 +109,21 @@ function parseArray(str) {
* @param {number} max The maximum value.
* returns {number} The clamped number.
*/
function clampValue(number, min, max) {
const clampValue = (number, min, max) => {
// @ts-ignore
if (Number.isNaN(parseInt(number))) return min;
return Math.max(min, Math.min(number, max));
}
};

/**
* Check if the given string is a valid gradient.
*
* @param {string[]} colors Array of colors.
* @returns {boolean} True if the given string is a valid gradient.
*/
function isValidGradient(colors) {
const isValidGradient = (colors) => {
return isValidHexColor(colors[1]) && isValidHexColor(colors[2]);
}
};

/**
* Retrieves a gradient if color has more than one valid hex codes else a single color.
Expand All @@ -132,7 +132,7 @@ function isValidGradient(colors) {
* @param {string} fallbackColor The fallback color.
* @returns {string | string[]} The gradient or color.
*/
function fallbackColor(color, fallbackColor) {
const fallbackColor = (color, fallbackColor) => {
let gradient = null;

let colors = color ? color.split(",") : [];
Expand All @@ -144,7 +144,7 @@ function fallbackColor(color, fallbackColor) {
(gradient ? gradient : isValidHexColor(color) && `#${color}`) ||
fallbackColor
);
}
};

/**
* Send GraphQL request to GitHub API.
Expand All @@ -153,15 +153,15 @@ function fallbackColor(color, fallbackColor) {
* @param {import('axios').AxiosRequestConfig['headers']} headers Request headers.
* @returns {Promise<any>} Request response.
*/
function request(data, headers) {
const request = (data, headers) => {
// @ts-ignore
return axios({
url: "https://api.github.com/graphql",
method: "post",
headers,
data,
});
}
};

/**
* Auto layout utility, allows us to layout things vertically or horizontally with
Expand All @@ -174,7 +174,7 @@ function request(data, headers) {
* @param {"column" | "row"?=} props.direction Direction to layout items.
* @returns {string[]} Array of items with proper layout.
*/
function flexLayout({ items, gap, direction, sizes = [] }) {
const flexLayout = ({ items, gap, direction, sizes = [] }) => {
let lastSize = 0;
// filter() for filtering out empty strings
return items.filter(Boolean).map((item, i) => {
Expand All @@ -186,7 +186,7 @@ function flexLayout({ items, gap, direction, sizes = [] }) {
lastSize += size + gap;
return `<g transform="${transform}">${item}</g>`;
});
}
};

/**
* Returns theme based colors with proper overrides and defaults.
Expand All @@ -201,7 +201,7 @@ function flexLayout({ items, gap, direction, sizes = [] }) {
* @param {string} args.fallbackTheme Fallback theme.
*
*/
function getCardColors({
const getCardColors = ({
title_color,
text_color,
icon_color,
Expand All @@ -210,7 +210,7 @@ function getCardColors({
ring_color,
theme,
fallbackTheme = "default",
}) {
}) => {
const defaultTheme = themes[fallbackTheme];
const selectedTheme = themes[theme] || defaultTheme;
const defaultBorderColor =
Expand Down Expand Up @@ -248,7 +248,7 @@ function getCardColors({
);

return { titleColor, iconColor, textColor, bgColor, borderColor, ringColor };
}
};

/**
* Split text over multiple lines based on the card width.
Expand All @@ -258,7 +258,7 @@ function getCardColors({
* @param {number} maxLines Maximum number of lines.
* @returns {string[]} Array of lines.
*/
function wrapTextMultiline(text, width = 59, maxLines = 3) {
const wrapTextMultiline = (text, width = 59, maxLines = 3) => {
const fullWidthComma = ",";
const encoded = encodeHTML(text);
const isChinese = encoded.includes(fullWidthComma);
Expand All @@ -283,7 +283,7 @@ function wrapTextMultiline(text, width = 59, maxLines = 3) {
// Remove empty lines if text fits in less than maxLines lines
const multiLineText = lines.filter(Boolean);
return multiLineText;
}
};

const noop = () => {};
// return console instance based on the environment
Expand Down Expand Up @@ -349,7 +349,7 @@ class MissingParamError extends Error {
* @param {number} fontSize Font size.
* @returns {number} Text length.
*/
function measureText(str, fontSize = 10) {
const measureText = (str, fontSize = 10) => {
// prettier-ignore
const widths = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
Expand Down Expand Up @@ -381,7 +381,7 @@ function measureText(str, fontSize = 10) {
)
.reduce((cur, acc) => acc + cur) * fontSize
);
}
};

/** @param {string} name */
const lowercaseTrim = (name) => name.toLowerCase().trim();
Expand All @@ -394,7 +394,7 @@ const lowercaseTrim = (name) => name.toLowerCase().trim();
* @param {number} perChunk Number of languages per column.
* @returns {Array<T>} Array of languages split in two columns.
*/
function chunkArray(arr, perChunk) {
const chunkArray = (arr, perChunk) => {
return arr.reduce((resultArray, item, index) => {
const chunkIndex = Math.floor(index / perChunk);

Expand All @@ -406,20 +406,20 @@ function chunkArray(arr, perChunk) {

return resultArray;
}, []);
}
};

/**
* Parse emoji from string.
*
* @param {string} str String to parse emoji from.
* @returns {string} String with emoji parsed.
*/
function parseEmojis(str) {
const parseEmojis = (str) => {
if (!str) throw new Error("[parseEmoji]: str argument not provided");
return str.replace(/:\w+:/gm, (emoji) => {
return toEmoji.get(emoji) || "";
});
}
};

export {
ERROR_CARD_LENGTH,
Expand Down
4 changes: 2 additions & 2 deletions src/fetchers/repo-fetcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ const urlExample = "/api/pin?username=USERNAME&amp;repo=REPO_NAME";
* @param {string} reponame GitHub repository name.
* @returns {Promise<import("./types").RepositoryData>} Repository data.
*/
async function fetchRepo(username, reponame) {
const fetchRepo = async (username, reponame) => {
if (!username && !reponame) {
throw new MissingParamError(["username", "repo"], urlExample);
}
Expand Down Expand Up @@ -100,7 +100,7 @@ async function fetchRepo(username, reponame) {
starCount: data.organization.repository.stargazers.totalCount,
};
}
}
};

export { fetchRepo };
export default fetchRepo;
6 changes: 3 additions & 3 deletions src/fetchers/stats-fetcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,12 +188,12 @@ const totalStarsFetcher = async (username, repoToHide) => {
* @param {boolean} include_all_commits Include all commits.
* @returns {Promise<import("./types").StatsData>} Stats data.
*/
async function fetchStats(
const fetchStats = async (
username,
count_private = false,
include_all_commits = false,
exclude_repo = [],
) {
) => {
if (!username) throw new MissingParamError(["username"]);

const stats = {
Expand Down Expand Up @@ -275,7 +275,7 @@ async function fetchStats(
});

return stats;
}
};

export { fetchStats };
export default fetchStats;
4 changes: 2 additions & 2 deletions src/fetchers/top-languages-fetcher.js
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ const fetcher = (variables, token) => {
* @param {string[]} exclude_repo List of repositories to exclude.
* @returns {Promise<import("./types").TopLangData>} Top languages data.
*/
async function fetchTopLanguages(username, exclude_repo = []) {
const fetchTopLanguages = async (username, exclude_repo = []) => {
if (!username) throw new MissingParamError(["username"]);

const res = await retryer(fetcher, { login: username });
Expand Down Expand Up @@ -136,7 +136,7 @@ async function fetchTopLanguages(username, exclude_repo = []) {
}, {});

return topLangs;
}
};

export { fetchTopLanguages };
export default fetchTopLanguages;
4 changes: 2 additions & 2 deletions src/translations.js
Original file line number Diff line number Diff line change
Expand Up @@ -367,9 +367,9 @@ const availableLocales = Object.keys(repoCardLocales["repocard.archived"]);
* @param {string} locale The locale to check.
* @returns {boolean} Boolean specifying whether the locale is available or not.
*/
function isLocaleAvailable(locale) {
const isLocaleAvailable = (locale) => {
return availableLocales.includes(locale.toLowerCase());
}
};

export {
isLocaleAvailable,
Expand Down