summaryrefslogtreecommitdiff
path: root/source/libs/utils.ts
diff options
context:
space:
mode:
authorGravatar Nick Taylor <nick@iamdeveloper.com> 2019-02-08 09:54:46 -0500
committerGravatar Federico Brigante <github@bfred.it> 2019-02-08 22:54:46 +0800
commit9f9d178aceae3d8771685f5a043f8dff10033453 (patch)
tree60d146ff342dd7cf4892749fff8fd11f3a5c0307 /source/libs/utils.ts
parent4c90b05ca14285fa98d370da70ca6770af08e1b4 (diff)
downloadrefined-github-9f9d178aceae3d8771685f5a043f8dff10033453.tar.gz
refined-github-9f9d178aceae3d8771685f5a043f8dff10033453.tar.zst
refined-github-9f9d178aceae3d8771685f5a043f8dff10033453.zip
Move to TypeScript (#1750)
Diffstat (limited to 'source/libs/utils.ts')
-rw-r--r--source/libs/utils.ts69
1 files changed, 69 insertions, 0 deletions
diff --git a/source/libs/utils.ts b/source/libs/utils.ts
new file mode 100644
index 00000000..421d9f66
--- /dev/null
+++ b/source/libs/utils.ts
@@ -0,0 +1,69 @@
+import select from 'select-dom';
+import onetime from 'onetime';
+import {isRepo, isPR, isIssue} from './page-detect';
+
+export const getUsername = onetime(() => select('meta[name="user-login"]').getAttribute('content'));
+
+export const getDiscussionNumber = () => (isPR() || isIssue()) && getCleanPathname().split('/')[3];
+
+// Drops leading and trailing slash to avoid /\/?/ everywhere
+export const getCleanPathname = () => location.pathname.replace(/^[/]|[/]$/g, '');
+
+// Parses a repo's subpage, e.g.
+// '/user/repo/issues/' -> 'issues'
+// '/user/repo/' -> ''
+// returns undefined if the path is not a repo
+export const getRepoPath = () => {
+ if (isRepo()) {
+ return getCleanPathname().split('/').slice(2).join('/');
+ }
+
+ return undefined;
+};
+
+export const getRepoBranch = () => {
+ const [type, branch] = getCleanPathname().split('/').slice(2);
+ if (isRepo() && type === 'tree') {
+ return branch;
+ }
+
+ return false;
+};
+
+export const getRepoURL = () => location.pathname.slice(1).split('/', 2).join('/');
+
+export const getOwnerAndRepo = () => {
+ const [, ownerName, repoName] = location.pathname.split('/', 3);
+ return {ownerName, repoName};
+};
+
+export const groupBy = (iterable, grouper) => {
+ const map = {};
+ for (const item of iterable) {
+ const key = grouper(item);
+ map[key] = map[key] || [];
+ map[key].push(item);
+ }
+
+ return map;
+};
+
+// Concats arrays but does so like a zipper instead of appending them
+// [[0, 1, 2], [0, 1]] => [0, 0, 1, 1, 2]
+// Like lodash.zip
+export const flatZip = (table, limit = Infinity) => {
+ const maxColumns = Math.max(...table.map(row => row.length));
+ const zipped = [];
+ for (let col = 0; col < maxColumns; col++) {
+ for (const row of table) {
+ if (row[col]) {
+ zipped.push(row[col]);
+ if (zipped.length === limit) {
+ return zipped;
+ }
+ }
+ }
+ }
+
+ return zipped;
+};