BUG : Rotation like tetris

// --- TETRIS T PIECE (spawn orientation) ---

// Using 1 for blocks, 0 for empty

let currentPiece = [
  [0, 1, 0],
  [1, 1, 1],
  [0, 0, 0],
];

// --- ROTATE FUNCTION (your version) ---

function rotate15degre() {
  for (let ligne = 0; ligne < currentPiece.length; ligne++) {
    for (let colonne = 0; colonne < currentPiece.length; colonne++) {
      currentPiece[ligne][colonne] =
        currentPiece[-colonne + currentPiece.length - 1][ligne];
    }
  }
}
// --- HELPER TO PRINT MATRIX ---

function printMatrix(matrix) {
  console.log(matrix.map((row) => row.join(" ")).join("\n"));
}

// --- TEST BEFORE ROTATION ---

console.log("Before rotation:");
// printMatrix(currentPiece);
console.table(currentPiece);
rotate15degre();
console.table(currentPiece);





Tetris : rotate with map !

// --- TETRIS T PIECE (spawn orientation) ---

// Using 1 for blocks, 0 for empty

let currentPiece = [
  [0, 1, 0],
  [1, 1, 1],
  [0, 0, 0],
];

// --- ROTATE FUNCTION (your version) ---

function rotate() {
  const rotated = currentPiece[0].map((_, i) =>
    currentPiece.map((row) => row[i]).reverse(),
  );
  currentPiece = rotated;
}

// --- HELPER TO PRINT MATRIX ---

function printMatrix(matrix) {
  console.log(matrix.map((row) => row.join(" ")).join("\n"));
}

// --- TEST BEFORE ROTATION ---

console.log("Before rotation:");
printMatrix(currentPiece);

// --- APPLY ROTATION ---

rotate();

// --- TEST AFTER ROTATION ---

console.log("\nAfter rotation 1:");
printMatrix(currentPiece);

// --- APPLY ROTATION ---

rotate();

// --- TEST AFTER ROTATION ---

console.log("\nAfter rotation 2:");
printMatrix(currentPiece);

// --- APPLY ROTATION ---

rotate();

// --- TEST AFTER ROTATION ---

console.log("\nAfter rotation 3:");
printMatrix(currentPiece);
// --- APPLY ROTATION ---

rotate();

// --- TEST AFTER ROTATION ---

console.log("\nAfter rotation:");
printMatrix(currentPiece);







Différence entre URL et file path.

Un chemin d'accès est une chaîne de caractères qui spécifie l'emplacement d'un fichier dans un système de fichiers. Il peut être absolu ou relatif. Voici un exemple de lecture d'un fichier à l'aide d'un chemin d'accès dans Node.js :

Une URL (Uniform Resource Locator) est une référence à une ressource web qui spécifie son emplacement sur un réseau informatique et un mécanisme pour la récupérer. 

Dans Node.js, vous pouvez également utiliser les URL pour les chemins d'accès aux fichiers, ce qui est particulièrement utile pour les projets de développement. 

import { readFile } from 'fs/promises';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

// URL for the current module
const currentModuleURL = new URL(import.meta.url);

// Convert the URL to a file path
const currentModulePath = dirname(fileURLToPath(currentModuleURL));

// Use the file path to read a file
const data = await readFile(`${currentModulePath}/2024-03-14-feed.json`, 'utf8');
console.log(data);

Dans ce deuxième exemple, import.meta.url fournit une URL pour le module en cours. Cette URL est ensuite convertie en chemin de fichier à l'aide de fileURLToPath, et le chemin de fichier est utilisé pour lire un fichier.

🥷La principale différence entre les deux est que les chemins d'accès aux fichiers sont spécifiques au système de

fichiers et sont utilisés pour lire/écrire des fichiers, tandis que les URL sont plus généraux et peuvent être utilisés pour

localiser des ressources sur Internet ou sur un réseau local, en plus du système de fichiers local.


high level await

 Exemple voir code

Cors : so simple

const cors = require('cors');

app.use(cors({ origin: /http:\/\/(127(\.\d){3}|localhost)/})); 

app.options('*', cors());


On remarque la regExp :  http:\/\/(127(\.\d){3}|localhost)

Soit  http:\/\/(127(\.\d){3} cad http://127.nb.nb.nb 

ou localhost

__dirname

 

__dirname 

n'est pas reconnu lorsque l'on passe en version de module EJS. Voici deux solutions possibles.

🪛Redéfinir __dirname 

Dans test.mjs

import { dirname } from "path";
import { fileURLToPath } from "url";
import { readFile } from "fs/promises";

const path = "/hello.txt";
const __dirname = dirname(fileURLToPath(import.meta.url));
const data = await readFile(__dirname + path);

console.log(data);
console.log(data.toString());


🪛Oublier __dirname 

import { URL } from "node:url";
import { readFile } from "node:fs/promises";

const path = "./hello.txt";
const data = await readFile(new URL(path, import.meta.url));

console.log(data);
console.log(data.toString());

DATE

const timestamp = new Date().getTime();
console.log(timestamp)

let DAY_FORMATTER = new Intl.DateTimeFormat(undefined, { weekday: "long",
month: "long" })
console.log(DAY_FORMATTER.format(timestamp))

DAY_FORMATTER = new Intl.DateTimeFormat(undefined, { dayPeriod: "short"
, weekday: "short", year: "numeric"
, month: "short", day: "numeric" })
console.log(DAY_FORMATTER.format(0))

Les valeurs possibles : 
{
  weekday: 'narrow' | 'short' | 'long',
  era: 'narrow' | 'short' | 'long',
  year: 'numeric' | '2-digit',
  month: 'numeric' | '2-digit' | 'narrow' | 'short' | 'long',
  day: 'numeric' | '2-digit',
  hour: 'numeric' | '2-digit',
  minute: 'numeric' | '2-digit',
  second: 'numeric' | '2-digit',
  timeZoneName: 'short' | 'long',

  // Time zone to express it in
  timeZone: 'Asia/Shanghai',
  // Force 12-hour or 24-hour
  hour12: true | false,
}

vite

npm create vite@latest

npm i

npm run dev



debug

 le module debug est un must ! 

https://www.npmjs.com/package/debug


La définition des espace de noms dépendra de votre terminal : 

cmd

set DEBUG=baseRange:arg,http & node app.js

 

git bash 

Si votre terminal est git bash lancer : 

DEBUG=baseRange:arg,http node app.js

 

PowerShell

Si votre terminal est PowerShell lancer : 

$env:DEBUG='baseRange:arg,http' ; node app.js


Github page.

 Création d'un déploiement. 



Autre idée, cloner tout simplement la branche master dans la branche gh-pages. that's it.


my-json-server


Créez son propre server JSON !

https://jsonplaceholder.typicode.com/


https://my-json-server.typicode.com/dupontdenis/myJsonServer

En action : https://github.com/dupontdenis/myJsonServer.git

npx


>npx lite-server

It will create a local web server and open your app in a browser.

Extension Rest Client

Créer un fichier app.js

const express = require('express');
const bodyParser = require('body-parser');
const app = express()

app.use(bodyParser.json());


const port = 3000

sayhello = function(pers){
    return `hello ${pers}`
}

app.post('/', (req, res) => {
  res.send(sayhello(req.body && req.body.pers || 'hi'))
})


app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)}) 

Mettre en place l'application :
  • npm init -y
  • npm install express
Dans un terminal lancez l'application :
  • node app.js


Ajouter l'extension Rest API.

Créer un fichier api.http

POST http://localhost:3000
Content-Type: application/json

{"pers":"denis"}

En cliquant sur le lien Send Request (pas sur http://localhost:3000), on obtient la réponse suivante.



Plus besoin de Postman pour ce type de test.


Autre exemple avec une authentification 







ES6 module in nodejs

 https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules/53826979#53826979

Deno is here !

 https://deno.land/

API for test

 https://dev.to/api/articles

Permet de charger une série d'articles !

module fs

 const fs = require("fs").promises;

const path = require("path");

async function findFiles(folderName) {
  const items = await fs.readdir(folderName, { withFileTypes: true });
  items.forEach((item) => {
    if (path.extname(item.name) === ".json") {
      console.log(`Found file: ${item.name} in folder: ${folderName}`);
    } else {
      findFiles(path.join(folderName, item.name));
    }
  });
}
findFiles("stores");

Considérons la structure : 


$ node index.js 
Found file: sales.json in folder: stores\201
Found file: sales.json in folder: stores\203
Found file: sales.json in folder: stores\201\204
Found file: sales.json in folder: stores\201\204\202

fetch/ asyn

Promise

  1. function getFromGitHub() {
  2.   const userName = 'dupontdenis';
  3.   const url = 'https://api.github.com/users';

  4.   fetch(`${url}/${userName}/repos`)
  5.     .then(reposResponse => {
  6.       return reposResponse.json();
  7.     })
  8.     .then(userRepos => {
  9.       console.log(userRepos[0].owner.avatar_url)
  10.       document.body.insertAdjacentHTML('afterbegin',`<img src=${userRepos[0].owner.avatar_url}>`)
  11.     })
  12.     .catch(err => {
  13.       console.log(err);
  14.     });
  15. }

  16. getFromGitHub();

Avec sync


  1. async function getFromGitHub() {
  2.   try {
  3.     const userName = 'dupontdenis';
  4.     const url = 'https://api.github.com/users';
  5.     const reposResponse = await fetch(`${url}/${userName}/repos`);
  6.     const userRepos = await reposResponse.json();

  7.           document.body.insertAdjacentHTML('afterbegin',`<img src=${userRepos[0].owner.avatar_url}>`)

  8.   } catch (error) {
  9.     console.log(error);
  10.   }
  11. }


  12. getFromGitHub();