-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathglobalFns.js
410 lines (320 loc) · 12.4 KB
/
globalFns.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/* eslint-disable no-useless-escape */
/* eslint-disable no-empty */
/* eslint-disable semi */
/* eslint-disable no-console */
/* eslint-disable indent */
import moment from 'moment';
import { getVideoThumb } from './components/LessonSection/Preview/utils';
import { SHOWABLE_LESSONS_STATUSES } from './globalVars';
import { getLinkPreview } from 'link-preview-js';
export const createPaginationArr = arr => {
let pgsArr = [];
let pgOfDataArr = [];
arr.forEach((val, index) => {
pgOfDataArr.push(val);
if ((pgOfDataArr?.length === 6) || (index === (arr?.length - 1))) {
pgsArr.push(structuredClone(pgOfDataArr));
pgOfDataArr = [];
}
});
return pgsArr;
};
export const getGpVids = lessons => {
let gpVideos = [];
for (const lesson of lessons) {
let lessonMultiMediaArr = [];
const { Section, Title, numID, ReleaseDate } = lesson;
if (Section?.preview?.Multimedia?.length && Section?.preview?.Multimedia.every(multiMediaItem => multiMediaItem !== null)) {
for (const media of Section.preview.Multimedia) {
const isTargetGpVidPresent = gpVideos?.length ? gpVideos.some(({ mainLink: gpVidMainLink }) => gpVidMainLink === media.mainLink) : false;
if (!isTargetGpVidPresent && (media.by === 'Galactic Polymath') && (media.type === 'video') && ((typeof media.mainLink === 'string') && media.mainLink.includes('youtube'))) {
lessonMultiMediaArr.push({
ReleaseDate: ReleaseDate,
lessonUnitTitle: Title,
videoTitle: media.title,
mainLink: media.mainLink,
description: media.description ?? media.lessonRelevance,
thumbnail: getVideoThumb(media.mainLink),
unitNumId: numID,
lessonNumId: (media.forLsn && Number.isInteger(+media.forLsn)) ? parseInt(media.forLsn) : null,
});
}
}
}
if (lessonMultiMediaArr?.length) {
gpVideos.push(...lessonMultiMediaArr);
}
}
return gpVideos.sort((videoA, videoB) => videoB.ReleaseDate - videoA.ReleaseDate);
};
export const getGpLessons = lessons => {
let lessonPartsForUI = [];
const todaysDate = new Date();
for (let lesson of lessons) {
if (!lesson?.LsnStatuses?.length || !SHOWABLE_LESSONS_STATUSES.includes(lesson.PublicationStatus)) {
continue;
}
let lessonParts = lesson?.Section?.['teaching-materials']?.Data?.lesson;
let lessonPartsFromClassRoomObj = lesson?.Section?.['teaching-materials']?.Data?.classroom?.resources?.[0]?.lessons;
if (lessonParts?.length) {
for (let lsnStatus of lesson.LsnStatuses) {
if (!SHOWABLE_LESSONS_STATUSES.includes(lsnStatus.status)) {
continue;
}
const lessonPart = lessonParts.find(({ lsnNum }) => lsnNum === lsnStatus.lsn);
const wasLessonReleased = moment(todaysDate).format('YYYY-MM-DD') > moment(lsnStatus.unit_release_date).format('YYYY-MM-DD');
if (lessonPart && wasLessonReleased) {
const lessonPartFromClassroomObj = lessonPartsFromClassRoomObj.find(({ lsn }) => lsn == lsnStatus.lsn);
let tags = Array.isArray(lessonPartFromClassroomObj?.tags?.[0]) ? lessonPartFromClassroomObj?.tags.flat() : lessonPartFromClassroomObj?.tags;
tags = tags?.length ? tags.filter(tag => tag) : tags;
const lessonPartForUI = {
tags: tags ?? null,
lessonPartPath: `/lessons/${lesson.locale}/${lesson.numID}#lesson_part_${lessonPart.lsnNum}`,
tile: lessonPartFromClassroomObj?.tile ?? 'https://storage.googleapis.com/gp-cloud/icons/Missing_Lesson_Tile_Icon.png',
lessonPartTitle: lessonPart.lsnTitle,
dur: lessonPart.lsnDur,
preface: lessonPart.lsnPreface,
lessonPartNum: lessonPart.lsnNum,
lessonTitle: lesson.Title,
subject: lesson.TargetSubject,
grades: lesson.ForGrades,
gradesOrYears: lesson.GradesOrYears,
status: lsnStatus.status,
};
lessonPartsForUI.push(lessonPartForUI);
}
}
}
}
let lessonParts = structuredClone(lessonPartsForUI);
if (lessonParts?.length) {
lessonParts = lessonParts.sort(({ sort_by_date: sortByDateLessonA }, { sort_by_date: sortByDateLessonB }) => {
let _sortByDateLessonA = new Date(sortByDateLessonA);
let _sortByDateLessonB = new Date(sortByDateLessonB);
if (_sortByDateLessonA > _sortByDateLessonB) {
return -1;
}
if (_sortByDateLessonA < _sortByDateLessonB) {
return 1;
}
return 0;
});
}
return lessonParts;
};
export const STATUSES_OF_SHOWABLE_LESSONS = ['Live', 'Beta', 'Upcoming'];
export const getShowableUnits = units => {
let uniqueUnits = [];
const todaysDate = new Date();
for (const unit of units) {
if (STATUSES_OF_SHOWABLE_LESSONS.includes(unit.PublicationStatus) &&
!uniqueUnits.some(uniqueUnit => unit.numID === uniqueUnit.numID) &&
(moment(unit.ReleaseDate).format('YYYY-MM-DD') <= moment(todaysDate).format('YYYY-MM-DD'))) {
uniqueUnits.push(unit);
}
}
return uniqueUnits;
};
export const getIsTypeValid = (val, targetType) => {
return typeof val === targetType;
};
export const getLinkPreviewObj = async (url = '') => {
try {
if (!url || (typeof url !== 'string')) {
throw new Error('Either received an empty string or an incorrect data type.')
}
const linkPreviewObj = await getLinkPreview(url);
return linkPreviewObj;
} catch (error) {
const errMsg = `An error has occurred in getting the link preview for given url. Error message: ${error}.`;
console.error(errMsg);
return { errMsg };
}
};
export const getIsValObj = val => (typeof val === 'object') && !Array.isArray(val) && (val !== null);
export const getObjVals = obj => {
const keys = Object.keys(obj);
let vals = [];
keys.forEach(key => {
const val = obj[key];
vals.push(val);
});
return vals;
};
/**
*
* @param {string} urlOriginWithPaths
* @param {[string, unknown][]} searchQuery
*/
export const constructUrlWithSearchQuery = (urlOriginWithPaths, searchQuery) => {
const url = new URL(urlOriginWithPaths);
for (const [key, val] of searchQuery) {
url.searchParams.append(key, val);
}
return url;
}
const searchParamsDefault = (typeof window === 'undefined') ? null : window.location.search;
export const getUrlParamVal = (searchParams = searchParamsDefault, paramName = '') => {
const urlSearchParams = new URLSearchParams(searchParams)
return urlSearchParams.get(paramName)
}
export const createObj = (keysAndValsArr = []) => {
if (!keysAndValsArr?.length) {
console.error('The array to create the object is empty.')
return null;
}
const isKeysAndValsArrValid = keysAndValsArr.every(keyAndVal => {
if (!Array.isArray(keyAndVal)) {
return false;
}
if (!['symbol', 'string'].includes(typeof keyAndVal[0])) {
return false;
}
return true;
})
if (!isKeysAndValsArrValid) {
console.error('Each value fo the `keysAndVals` arr must have the following format: [key: string | symbol, value: any]')
return null;
}
return keysAndValsArr.reduce((obj, currentKeyAndVal) => {
const [key, val] = currentKeyAndVal;
obj[key.trim()] = val;
return obj;
}, {})
}
export const getIsParsable = val => {
try {
JSON.parse(val);
return true;
} catch (error) {
console.error('Not parsable. Reason: ', error);
return false;
}
}
export const getIsParsableToVal = (val, valType, isArr) => {
try {
const parsedVal = JSON.parse(val);
if (typeof parsedVal !== valType) {
throw Error('Incorrect parsed value type.')
}
if (isArr) {
return Array.isArray(parsedVal);
}
if (valType === 'object') {
return getIsValObj(parsedVal);
}
return true;
} catch (error) {
console.error('Not parsable. Reason: ', error);
return false;
}
}
export const removeHtmlTags = str => str.replace(/<[^>]*>/g, '');
export const sleep = milliseconds => {
console.log(`Will sleep for: ${milliseconds} ms`);
return new Promise(resolve => {
setTimeout(resolve, milliseconds);
});
};
export const getIsObj = val => !!val && (typeof val === 'object');
/**
* @param {import('next/router').NextRouter} router
*/
export const resetUrl = router => {
const url = router.asPath;
router.replace(url.split('?')[0]);
}
/**
* @param {Map<string, any>} map
* @return {object}
*/
export const convertMapToObj = map => Object.fromEntries(map.entries())
/**
* @param {import('next/router').NextRouter} router
* @param {string} urlField
* @returns {string[]}
* */
export const getAllUrlVals = (router, willCreateSubTuples) => {
const pathsStr = router.asPath.split('?')[1];
let urlKeysAndVals = pathsStr?.split('&');
if (urlKeysAndVals?.length && willCreateSubTuples) {
const urlKeysAndValsTuples = urlKeysAndVals.map(keyAndValStr => {
return keyAndValStr.split('=');
});
return urlKeysAndValsTuples;
}
return urlKeysAndVals;
};
/**
*
* @param {any[]} arr
* @param {number} chunkSize
* @returns {any[][]}
*/
export const getChunks = (arr, chunkSize) => {
const chunks = [];
let chunkWindow = [];
for (let index = 0; index < arr.length; index++) {
let val = arr[index];
if (chunkWindow.length === chunkSize) {
chunks.push(chunkWindow);
chunkWindow = [];
}
chunkWindow.push(val);
if (index === (arr.length - 1)) {
chunks.push(chunkWindow);
}
}
return chunks;
};
export const createChunks = (arr, chunkSize) => {
const chunks = [];
let chunkWindow = [];
for (let index = 0; index < arr.length; index++) {
let val = arr[index];
if (chunkWindow.length === chunkSize) {
chunks.push(chunkWindow);
chunkWindow = [];
}
chunkWindow.push(val);
if (index === (arr.length - 1)) {
chunks.push(chunkWindow);
}
}
return chunks;
};
/**
* @param {import('next/router').NextRouter} router
* @param {string} targetKey
*/
export const getTargetKeyValFromUrl = (router, targetKey) => {
const urlVals = getAllUrlVals(router)?.flatMap(urlVal => urlVal.split('='));
const urlValsChunks = urlVals?.length ? getChunks(urlVals, 2) : []
const targetKeyVal = urlValsChunks.find(([key]) => key === targetKey)
return targetKeyVal;
}
export const validateEmail = (email) => {
return email.match(
/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
);
};
export const getIsWithinParentElement = (element, specifier, classNameOrId = 'className') => {
if (!element?.parentElement || (element?.parentElement && (classNameOrId in element.parentElement) && (element?.parentElement[classNameOrId] === undefined))) {
console.error('Reached end of document.');
return false;
}
if (
((element?.parentElement != null) && (typeof element?.parentElement === 'object') && (typeof element.parentElement[classNameOrId] === 'string')) &&
element.parentElement[classNameOrId].includes(specifier)
) {
return true;
}
return getIsWithinParentElement(element.parentElement, specifier, classNameOrId);
}
export const waitWithExponentialBackOff = async (num = 1) => {
const randomNumMs =
Math.floor(Math.random() * (5_500 - 1000 + 1)) + 1000;
const waitTime = randomNumMs + (num * 1_000);
await sleep(waitTime);
return num + 1;
}