إزالة ملاحظة
جزء من قسم أساسيات 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)}`);التحدي
سهل- يحذف
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);
}
يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.