Skip to content

Commit

Permalink
feat(challenge36): add solution on trackby
Browse files Browse the repository at this point in the history
  • Loading branch information
thomas committed Oct 3, 2023
1 parent 0a5bc85 commit c062613
Show file tree
Hide file tree
Showing 30 changed files with 564 additions and 20 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ If you would like to propose a challenge, this project is open source, so feel f
## Challenges

Check [all 35 challenges](https://angular-challenges.vercel.app/)
Check [all 36 challenges](https://angular-challenges.vercel.app/)

## Contributors ✨

Expand Down
36 changes: 36 additions & 0 deletions apps/performance/ngfor-optimize/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"extends": ["../../../.eslintrc.json"],
"ignorePatterns": ["!**/*"],
"overrides": [
{
"files": ["*.ts"],
"rules": {
"@angular-eslint/directive-selector": [
"error",
{
"type": "attribute",
"prefix": "app",
"style": "camelCase"
}
],
"@angular-eslint/component-selector": [
"error",
{
"type": "element",
"prefix": "app",
"style": "kebab-case"
}
]
},
"extends": [
"plugin:@nx/angular",
"plugin:@angular-eslint/template/process-inline-templates"
]
},
{
"files": ["*.html"],
"extends": ["plugin:@nx/angular-template"],
"rules": {}
}
]
}
13 changes: 13 additions & 0 deletions apps/performance/ngfor-optimize/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# NgFor Optimization

> Author: Thomas Laforge
### Run Application

```bash
npx nx serve performance-ngfor-optimize
```

### Documentation and Instruction

Challenge documentation is [here](https://angular-challenges.vercel.app/challenges/angular-performance/36-ngfor-optimize/).
22 changes: 22 additions & 0 deletions apps/performance/ngfor-optimize/jest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/* eslint-disable */
export default {
displayName: 'performance-ngfor-optimize',
preset: '../../../jest.preset.js',
setupFilesAfterEnv: ['<rootDir>/src/test-setup.ts'],
coverageDirectory: '../../../coverage/apps/performance/ngfor-optimize',
transform: {
'^.+\\.(ts|mjs|js|html)$': [
'jest-preset-angular',
{
tsconfig: '<rootDir>/tsconfig.spec.json',
stringifyContentPathRegex: '\\.(html|svg)$',
},
],
},
transformIgnorePatterns: ['node_modules/(?!.*\\.mjs$)'],
snapshotSerializers: [
'jest-preset-angular/build/serializers/no-ng-attributes',
'jest-preset-angular/build/serializers/ng-snapshot',
'jest-preset-angular/build/serializers/html-comment',
],
};
99 changes: 99 additions & 0 deletions apps/performance/ngfor-optimize/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
{
"name": "performance-ngfor-optimize",
"$schema": "../../../node_modules/nx/schemas/project-schema.json",
"projectType": "application",
"prefix": "app",
"sourceRoot": "apps/performance/ngfor-optimize/src",
"tags": [],
"targets": {
"build": {
"executor": "@angular-devkit/build-angular:browser",
"outputs": ["{options.outputPath}"],
"options": {
"outputPath": "dist/apps/performance/ngfor-optimize",
"index": "apps/performance/ngfor-optimize/src/index.html",
"main": "apps/performance/ngfor-optimize/src/main.ts",
"polyfills": ["zone.js"],
"tsConfig": "apps/performance/ngfor-optimize/tsconfig.app.json",
"assets": [
"apps/performance/ngfor-optimize/src/favicon.ico",
"apps/performance/ngfor-optimize/src/assets"
],
"styles": [
"apps/performance/ngfor-optimize/src/styles.scss",
"./node_modules/@angular/material/prebuilt-themes/indigo-pink.css"
],
"scripts": [],
"allowedCommonJsDependencies": ["seedrandom"]
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"buildOptimizer": false,
"optimization": false,
"vendorChunk": true,
"extractLicenses": false,
"sourceMap": true,
"namedChunks": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"executor": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"browserTarget": "performance-ngfor-optimize:build:production"
},
"development": {
"browserTarget": "performance-ngfor-optimize:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"executor": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "performance-ngfor-optimize:build"
}
},
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": [
"apps/performance/ngfor-optimize/**/*.ts",
"apps/performance/ngfor-optimize/**/*.html"
]
}
},
"test": {
"executor": "@nx/jest:jest",
"outputs": ["{workspaceRoot}/coverage/{projectRoot}"],
"options": {
"jestConfig": "apps/performance/ngfor-optimize/jest.config.ts",
"passWithNoTests": true
},
"configurations": {
"ci": {
"ci": true,
"codeCoverage": true
}
}
}
}
}
58 changes: 58 additions & 0 deletions apps/performance/ngfor-optimize/src/app/app.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { Component, OnInit, inject } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { PersonService } from './list.service';
import { PersonListComponent } from './person-list.component';

@Component({
standalone: true,
imports: [
PersonListComponent,
FormsModule,
MatFormFieldModule,
MatInputModule,
],
providers: [PersonService],
selector: 'app-root',
template: `
<h1 class="font-semibold text-center text-3xl" title="Title">
List of Persons
</h1>
<mat-form-field class="w-3/4">
<input
placeholder="Add one member to the list"
matInput
type="text"
[(ngModel)]="label"
(keydown)="handleKey($event)" />
</mat-form-field>
<app-person-list
class="max-w-2xl w-3/4"
[persons]="persons()"
(delete)="personService.deletePerson($event)"
(update)="personService.updatePerson($event)" />
`,
host: {
class: 'flex items-center flex-col gap-5',
},
})
export class AppComponent implements OnInit {
readonly personService = inject(PersonService);
readonly persons = this.personService.persons;

label = '';

ngOnInit(): void {
this.personService.loadPersons();
}

handleKey(event: any) {
if (event.keyCode === 13) {
this.personService.addPerson(this.label);
this.label = '';
}
}
}
6 changes: 6 additions & 0 deletions apps/performance/ngfor-optimize/src/app/app.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { ApplicationConfig } from '@angular/core';
import { provideAnimations } from '@angular/platform-browser/animations';

export const appConfig: ApplicationConfig = {
providers: [provideAnimations()],
};
15 changes: 15 additions & 0 deletions apps/performance/ngfor-optimize/src/app/generateList.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { randEmail, randFirstName } from '@ngneat/falso';
import { Person } from './person.model';

export function generateList() {
const arr: Person[] = [];

for (let i = 0; i < 50; i++) {
arr.push({
email: randEmail(),
name: randFirstName(),
});
}

return arr;
}
44 changes: 44 additions & 0 deletions apps/performance/ngfor-optimize/src/app/list.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Injectable, inject, signal } from '@angular/core';
import { randEmail, randFirstName } from '@ngneat/falso';
import { generateList } from './generateList';
import { Person } from './person.model';

@Injectable()
export class PersonService {
private readonly fakeBackend = inject(FakeBackendService);
readonly persons = signal<Person[]>([]);

loadPersons() {
this.persons.set(generateList());
}

deletePerson(email: string) {
this.persons.set(
this.fakeBackend
.returnNewList(this.persons())
.filter((p) => p.email !== email)
);
}

updatePerson(email: string) {
this.persons.set(
this.fakeBackend
.returnNewList(this.persons())
.map((p) => (p.email === email ? { email, name: randFirstName() } : p))
);
}

addPerson(name: string) {
this.persons.set([
{ email: randEmail(), name },
...this.fakeBackend.returnNewList(this.persons()),
]);
}
}

@Injectable({ providedIn: 'root' })
export class FakeBackendService {
returnNewList = (input: Person[]): Person[] => [
...input.map((i) => ({ ...i })),
];
}
37 changes: 37 additions & 0 deletions apps/performance/ngfor-optimize/src/app/person-list.component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Component, EventEmitter, Input, Output } from '@angular/core';

import { CommonModule } from '@angular/common';
import { Person } from './person.model';

@Component({
selector: 'app-person-list',
standalone: true,
imports: [CommonModule],
template: `
<div
*ngFor="let person of persons"
class="flex justify-between items-center border-b">
<h3>{{ person.name }}</h3>
<div class="flex gap-10 py-1">
<button
class="border rounded-md p-2 bg-blue-500 text-white"
(click)="update.emit(person.email)">
UPDATE
</button>
<button
class="border rounded-md p-2 bg-red-500 text-white"
(click)="delete.emit(person.email)">
DELETE
</button>
</div>
</div>
`,
host: {
class: 'w-full flex flex-col',
},
})
export class PersonListComponent {
@Input() persons: Person[] = [];
@Output() delete = new EventEmitter<string>();
@Output() update = new EventEmitter<string>();
}
4 changes: 4 additions & 0 deletions apps/performance/ngfor-optimize/src/app/person.model.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface Person {
email: string;
name: string;
}
Empty file.
Binary file added apps/performance/ngfor-optimize/src/favicon.ico
Binary file not shown.
13 changes: 13 additions & 0 deletions apps/performance/ngfor-optimize/src/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>performance-ngfor-optimize</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
</body>
</html>
7 changes: 7 additions & 0 deletions apps/performance/ngfor-optimize/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';

bootstrapApplication(AppComponent, appConfig).catch((err) =>
console.error(err)
);
5 changes: 5 additions & 0 deletions apps/performance/ngfor-optimize/src/styles.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
@tailwind base;
@tailwind components;
@tailwind utilities;

/* You can add global styles to this file, and also import other style files */
2 changes: 2 additions & 0 deletions apps/performance/ngfor-optimize/src/test-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import '@testing-library/jest-dom';
import 'jest-preset-angular/setup-jest';
14 changes: 14 additions & 0 deletions apps/performance/ngfor-optimize/tailwind.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const { createGlobPatternsForDependencies } = require('@nx/angular/tailwind');
const { join } = require('path');

/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
join(__dirname, 'src/**/!(*.stories|*.spec).{ts,html}'),
...createGlobPatternsForDependencies(__dirname),
],
theme: {
extend: {},
},
plugins: [],
};
Loading

0 comments on commit c062613

Please sign in to comment.