Skip to content

Commit

Permalink
refactor: use lodash for isEmpty/Undefined (#171)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidlj95 authored Nov 9, 2023
1 parent d1284db commit 1769631
Show file tree
Hide file tree
Showing 17 changed files with 86 additions and 64 deletions.
20 changes: 20 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,12 @@
"@fortawesome/free-solid-svg-icons": "^6.4.2",
"@ngaox/seo": "^5.0.0",
"@nguniversal/express-engine": "^16.2.0",
"@types/lodash-es": "^4.17.11",
"@unpic/core": "^0.0.35",
"compression": "^1.7.4",
"express": "^4.15.2",
"gardevoir": "^1.0.0",
"lodash-es": "^4.17.21",
"rxjs": "~7.8.0",
"swiper": "^11.0.3",
"tslib": "^2.3.0",
Expand Down
15 changes: 8 additions & 7 deletions scripts/src/imagekit.mts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { FileObject, ImageKitOptions } from 'imagekit/dist/libs/interfaces'
import { ImageAsset } from '../../src/app/common/images/image-asset.js'
import { ImageCdnApi } from './image-cdn-api.mjs'
import { URLSearchParams } from 'url'
import { isEmpty } from 'lodash-es'

const { IMAGEKIT_URL } = imagesCdnConfigPkg

Expand Down Expand Up @@ -50,17 +51,17 @@ export class Imagekit implements ImageCdnApi {
): Promise<ReadonlyArray<ImageAsset>> {
Log.group('Searching for images inside "%s" path', path)
const imageAssets = await this.listImageAssetsInPath(path)
imageAssets.length > 0
? Log.info('Found %d images', imageAssets.length)
: Log.info('No images found')
isEmpty(imageAssets)
? Log.info('No images found')
: Log.info('Found %d images', imageAssets.length)
const imagesFromDirectories: ImageAsset[] = []
if (includeSubdirectories) {
const directoryNames = await this.listDirectoryNamesInPath(path)
if (directoryNames.length > 0) {
if (isEmpty(directoryNames)) {
Log.info('No directories found')
} else {
Log.info('Found %d directories', directoryNames.length)
Log.info('Scanning directories...')
} else {
Log.info('No directories found')
}
Log.groupEnd()
for (const directoryName of directoryNames) {
Expand Down Expand Up @@ -108,7 +109,7 @@ export class Imagekit implements ImageCdnApi {
const alt = (fileObject.customMetadata as CustomMetadata)?.alt
const altMetadata: Pick<ImageAsset, 'alt'> = {}
// Avoid adding if empty string to save some space
if (!!alt && alt.length > 0) {
if (!isEmpty(alt?.trim())) {
altMetadata.alt = alt
}
// Point to specific file version
Expand Down
2 changes: 1 addition & 1 deletion scripts/src/json-file.mts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export class JsonFile implements FileReader, FileWriter {
return JSON.parse(await readFile(this.filepath, 'utf-8'))
} catch (error) {
Log.warn('Unable to read file %s', this.filepath)
return undefined
return
}
}

Expand Down
9 changes: 5 additions & 4 deletions scripts/src/project-list-item-extra-data-generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Log } from './log.mjs'
import { Project } from '../../src/app/projects/project.js'
import previewJson from '../../src/data/assets-collections/preview.json' assert { type: 'json' }
import projectImageAssetPkg from '../../src/app/projects/project-page/project-image-asset.js'
import { isEmpty, isUndefined } from 'lodash-es'

const { ProjectImageAsset } = projectImageAssetPkg

Expand Down Expand Up @@ -37,7 +38,7 @@ export class ProjectListItemExtraDataGenerator {
}

private async getImagesByGroups(): Promise<ImagesByGroups> {
if (!this._imagesByGroups) {
if (isUndefined(this._imagesByGroups)) {
const images = await this.getImages()
const preview: ImageAsset[] = []
const others: ImageAsset[] = []
Expand All @@ -61,7 +62,7 @@ export class ProjectListItemExtraDataGenerator {
}

private async getImagesResource(): Promise<Resource | null> {
if (this._imagesResource === undefined) {
if (isUndefined(this._imagesResource)) {
const imagesResource =
(await this.resource.childCollection.getResource(
this.resourceImagesGenerator.basename,
Expand All @@ -88,12 +89,12 @@ export class ProjectListItemExtraDataGenerator {
}

private async hasOtherImagesApartFromPreview(): Promise<boolean> {
return (await this.getImagesByGroups()).others.length > 0
return !isEmpty((await this.getImagesByGroups()).others)
}

private async hasVideos(): Promise<boolean> {
const project = (await this.resource.getData()) as Project
return !!project.youtubePlaylistId
return !isEmpty(project.youtubePlaylistId?.trim())
}

private async removePreviewImages(): Promise<void> {
Expand Down
3 changes: 2 additions & 1 deletion scripts/src/resource-collection-list-generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { ResourceCollection } from './resource-collection.mjs'
import { join } from 'path'
import { Resource } from './resource.mjs'
import { Log } from './log.mjs'
import { isEmpty } from 'lodash-es'

export class ResourceCollectionListGenerator {
constructor(
Expand Down Expand Up @@ -40,7 +41,7 @@ export class ResourceCollectionListGenerator {
if (this.listItemExtraDataGenerator) {
Log.info('Generating and appending extra data')
const listItemExtraData = await this.listItemExtraDataGenerator(resource)
if (!listItemExtraData || Object.keys(listItemExtraData).length === 0) {
if (isEmpty(listItemExtraData)) {
Log.warn('No extra data generated')
}
// Small trick given I know resource data is JSON
Expand Down
3 changes: 2 additions & 1 deletion scripts/src/routes-file-generator.mts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import path from 'path'
import { getRepositoryRootDir } from './get-repository-root-dir.mjs'
import { readdir, readFile, writeFile } from 'fs/promises'
import directoriesPkg from '../../src/app/common/directories.js'
import { isEmpty } from 'lodash-es'

const { CONTENTS_DIR, PROJECTS_DIR } = directoriesPkg

Expand Down Expand Up @@ -36,7 +37,7 @@ export class RoutesFileGenerator {
path.join(this.PROJECTS_PATH, projectDir.name),
{ withFileTypes: true },
)
return projectDirFiles.length > 0 ? projectDir.name : ''
return !isEmpty(projectDirFiles) ? projectDir.name : ''
}),
)
).filter((projectDir) => projectDir.length)
Expand Down
19 changes: 9 additions & 10 deletions src/app/about-page/add-open-graph-profile-metadata-from-author.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { IPageSeoData } from '@ngaox/seo'
import { MetaDefinition } from '@angular/platform-browser'
import { isEmpty } from 'lodash-es'

interface OpenGraphProfileMetadata {
readonly firstName: string
Expand All @@ -13,28 +14,30 @@ export function addOpenGraphProfileMetadata(
openGraphProfileMetadata: OpenGraphProfileMetadata,
): IPageSeoData {
const extras: MetaDefinition[] = []
if (isNonEmptyString(openGraphProfileMetadata.firstName)) {
if (!isEmpty(openGraphProfileMetadata.firstName)) {
extras.push({
property: 'og:profile:first_name',
content: openGraphProfileMetadata.firstName,
})
}
if (isNonEmptyString(openGraphProfileMetadata.lastName)) {
if (!isEmpty(openGraphProfileMetadata.lastName.trim())) {
extras.push({
property: 'og:profile:last_name',
content: openGraphProfileMetadata.lastName,
})
}
if (isNonEmptyString(openGraphProfileMetadata.gender)) {
if (!isEmpty(openGraphProfileMetadata.gender?.trim())) {
extras.push({
property: 'og:profile:gender',
content: openGraphProfileMetadata.gender,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
content: openGraphProfileMetadata.gender!,
})
}
if (isNonEmptyString(openGraphProfileMetadata.username)) {
if (!isEmpty(openGraphProfileMetadata.username?.trim())) {
extras.push({
property: 'og:profile:username',
content: openGraphProfileMetadata.username,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
content: openGraphProfileMetadata.username!,
})
}

Expand All @@ -44,7 +47,3 @@ export function addOpenGraphProfileMetadata(
extra: [...(metadata.extra ?? []), ...extras],
}
}

function isNonEmptyString(string: string | undefined): string is string {
return string !== undefined && string.trim().length > 0
}
3 changes: 2 additions & 1 deletion src/app/common/css/css-min-max-media-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { CssMinWidthMediaFeature } from './css-min-width-media-feature'
import { CssMaxWidthMediaFeature } from './css-max-width-media-feature'
import { CssMediaQuery } from './css-media-query'
import { CssUnit } from './unit/css-unit'
import { isUndefined } from 'lodash-es'

export class CssMinMaxMediaQuery<
MinUnit extends CssUnit,
Expand Down Expand Up @@ -51,7 +52,7 @@ export class CssMinMaxMediaQuery<

public toString(): string {
const mediaFeatures = [this.min, this.max].filter(
(mediaFeature) => !!mediaFeature,
(mediaFeature) => !isUndefined(mediaFeature),
)
if (mediaFeatures.length === 1) {
return mediaFeatures.join('')
Expand Down
8 changes: 5 additions & 3 deletions src/app/common/html/html-image-sizes-single-attribute.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { CssMediaQuery } from '../css/css-media-query'
import { CssUnit } from '../css/unit/css-unit'
import { isDefined } from '../is-defined'
import { isUndefined } from 'lodash-es'

export class HtmlImageSizesSingleAttribute {
constructor(
Expand All @@ -9,7 +9,9 @@ export class HtmlImageSizesSingleAttribute {
) {}

public toString(): string {
const parts = [this.mediaQuery, this.width].filter(isDefined)
return parts.map((part) => part.toString()).join(' ')
if (isUndefined(this.mediaQuery)) {
return this.width.toString()
}
return [this.mediaQuery, this.width].join(' ')
}
}
3 changes: 0 additions & 3 deletions src/app/common/is-defined.ts

This file was deleted.

5 changes: 1 addition & 4 deletions src/app/common/routing/get-metadata-from-json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,6 @@ export function getMetadataFromJson(
...jsonMetadata,
url: getCanonicalUrlForPath(...pathSegments),
title: getTitle(jsonMetadata.title),
keywords:
!!jsonMetadata.keywords && jsonMetadata.keywords.length
? jsonMetadata.keywords.join(', ')
: undefined,
keywords: jsonMetadata.keywords?.join(', '),
}
}
5 changes: 3 additions & 2 deletions src/app/common/routing/get-title.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import defaultMetadata from '../../../data/misc/metadata.json'
import { isEmpty } from 'lodash-es'

export function getTitle(pageTitle: string) {
if (!pageTitle || pageTitle.length === 0) {
export function getTitle(pageTitle: string | undefined | null) {
if (isEmpty(pageTitle?.trim())) {
return defaultMetadata.siteName
}
return `${pageTitle} | ${defaultMetadata.siteName}`
Expand Down
14 changes: 8 additions & 6 deletions src/app/common/social/social.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
faLinkedinIn,
faTiktok,
} from '@fortawesome/free-brands-svg-icons'
import { isEmpty } from 'lodash-es'

@Injectable({
providedIn: 'root',
Expand All @@ -30,19 +31,20 @@ export class SocialService {
this.isSocialName(author.social.preferred)
) {
const mainUsername = author.social[author.social.preferred]
if (!!mainUsername && mainUsername.trim().length > 0)
if (!isEmpty(mainUsername?.trim()))
return this.mapFromNameAndUsername(
author.social.preferred,
mainUsername,
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
mainUsername!,
)
}
const sortedSocials = Array.from(socials).sort(
(a, b) =>
(this.mainLinkPreferences.get(a.name) ?? 0) -
(this.mainLinkPreferences.get(b.name) ?? 0),
)
if (sortedSocials.length === 0) {
return undefined
if (isEmpty(sortedSocials)) {
return
}
return sortedSocials[0]
}
Expand All @@ -56,8 +58,8 @@ export class SocialService {
)
return entries
.filter(
([name, username]) =>
!!name && name.length > 0 && !!username && username.length > 0,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
([_, username]) => !isEmpty(username?.trim()),
)
.map(([name, username]) =>
this.mapFromNameAndUsername(name, username as string),
Expand Down
15 changes: 5 additions & 10 deletions src/app/projects/images-swiper/images-swiper.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
} from 'swiper/modules'
import { ResponsiveImageAttributes } from '../../common/images/responsive-image-attributes'
import { ImageAsset } from '../../common/images/image-asset'
import { isEmpty, isNumber } from 'lodash-es'

// There's no fancier way to install Web Components in Angular :P
// https://stackoverflow.com/a/75353889/3263250
Expand Down Expand Up @@ -75,11 +76,8 @@ export class ImagesSwiperComponent implements OnChanges {
const defaultSlidesPerView = swiperOptions.slidesPerView
const allSlidesPerView = breakpointSlidesPerViews
.concat([defaultSlidesPerView])
.filter(
(slidesPerView): slidesPerView is number =>
slidesPerView !== undefined && slidesPerView !== 'auto',
)
if (allSlidesPerView.length === 0) {
.filter(isNumber)
if (isEmpty(allSlidesPerView)) {
return null
}
return Math.max(...allSlidesPerView)
Expand All @@ -89,14 +87,11 @@ export class ImagesSwiperComponent implements OnChanges {
swiperOptions: SwiperOptions,
maxSlidesPerView: number | null,
): SwiperOptions {
if (
swiperOptions.loop !== undefined ||
swiperOptions.rewind !== undefined
) {
if (!isEmpty(swiperOptions.loop) || !isEmpty(swiperOptions.rewind)) {
return swiperOptions
}
const loop =
!!this.images &&
!isEmpty(this.images) &&
maxSlidesPerView !== null &&
this.images.length > maxSlidesPerView * 2
return {
Expand Down
Loading

0 comments on commit 1769631

Please sign in to comment.