Menu
CoddyTech

הסרת הערה

חלק מהיחידה יסודות Node.js במסלול ה-Node.js של Coddy. שיעור 12 מתוך 24.

done 2 אמור להסיר את ההערה 2, ואנשים מקלידים כל דבר אחרי done.

ארגומנטים הם מחרוזות: Number('2') הוא 2 ו-Number('two') הוא NaN. Number.isInteger דוחה את NaN ואת 2.5 בבדיקה אחת; ואז בודקים את הטווח. רשימות נספרות מ-1 ומערכים מ-0, לכן ההערה n נמצאת באינדקס n - 1, ו-splice(i, 1) מסיר אותה.

// node seat.js 4
const seat = Number(process.argv[2]);
if (!Number.isInteger(seat) || seat < 1 || seat > 30) {
    console.error(`No seat ${process.argv[2]}`);
    process.exit(1);
}
console.log(`Row ${Math.ceil(seat / 6)}`);
challenge icon

אתגר

קל
  • done <n> מסירה את הפתק שמספרו n, שומרת ומדפיסה Done: <text>.
  • מילה שאינה פתק (abc, 0, 2.5, מספר גדול ממספר הפתקים) מדפיסה No note <word> אל stderr ויוצאת עם 1, בלי לשנות דבר.

הריצו done 1, ואז list. לאחר מכן נסו done abc.

נסו בעצמכם

// כלי ההערות שלך מתחיל כאן.
import { rmSync } from 'node:fs';
import path from 'node:path';
import { formatNote } from './format.js';
import stats from './legacy/stats.cjs';
import store from './store.js';

const [command, ...words] = process.argv.slice(2);
const text = words.join(' ');

if (command === 'add') {
    const n = store.add(text);
    console.log(`Saved note ${n}.`);
} else if (command === 'list') {
    const owner = process.env.NOTES_OWNER ?? 'you';
    console.log(`Notes for ${owner}`);
    if (store.notes.length === 0) {
        console.log('No notes yet');
    }
    store.notes.forEach((note, i) => console.log(formatNote(i + 1, note)));
} else if (command === 'where') {
    const file = path.join(process.cwd(), 'notes.json');
    console.log(file);
    console.log(path.basename(file));
} else if (command === 'stats') {
    console.log(`${store.notes.length} notes, ${stats.countWords(store.notes)} words`);
} else if (command === 'clear') {
    rmSync('notes.json', { force: true });
    console.log('Deleted notes.json');
} else {
    if (command) {
        console.error(`Unknown command: ${command}`);
    }
    console.error('Usage: node notes.js <command> [words]');
    process.exit(1);
}
quiz iconבחנו את עצמכם

השיעור הזה כולל חידון קצר. התחילו את השיעור כדי לענות עליו ולעקוב אחרי ההתקדמות.

כל השיעורים ביחידה יסודות Node.js