Write two small generic helpers and use them on lists of words and of numbers.
What to build
A program that applies the same helpers to two kinds of list.
Requirements
- Write
lastN<T>(items: T[], n: number): T[], the last n items (all of them if there are fewer), andcountWhere<T>(items: T[], test: (item: T) => boolean): number. - Print
last words: ...(joined by spaces) andlast numbers: ...(joined by spaces) with k items each, thenlong words: C(words longer than 3 letters) andeven numbers: C.
Input
Line 1: k. Line 2: words separated by spaces. Line 3: whole numbers separated by spaces.
Output
Four lines.
Constraints
0 ≤ k ≤ 100; each list has 1 to 100 items.
Example
Input:
2
the quick brown fox
1 2 3 4 5
Output:
last words: brown fox
last numbers: 4 5
long words: 2
even numbers: 2
Why it works
One generic function works for string[] and number[] alike, and the callback's parameter type is inferred from the list, so word.length and n % 2 are both checked.
Examples
Example 1 · Input
2 the quick brown fox 1 2 3 4 5
Expected output
last words: brown fox last numbers: 4 5 long words: 2 even numbers: 2
Example 2 · Input
10 hi -2 0 7
Expected output
last words: hi last numbers: -2 0 7 long words: 0 even numbers: 2
Hints
Hint 1
lastN<T>(items: T[], n: number): T[] can use slice with a negative start; check n = 0.
Hint 2
countWhere<T>(items: T[], test: (item: T) => boolean): number.
Solution
Show one correct solution (try it yourself first)
const read = (): string => prompt() ?? "";
function lastN<T>(items: T[], n: number): T[] {
return n === 0 ? [] : items.slice(-n);
}
function countWhere<T>(items: T[], test: (item: T) => boolean): number {
let count = 0;
for (const item of items) if (test(item)) count++;
return count;
}
const k = Number(read());
const words: string[] = read().split(" ");
const numbers: number[] = read().split(" ").map(Number);
console.log("last words: " + lastN(words, k).join(" "));
console.log("last numbers: " + lastN(numbers, k).join(" "));
console.log("long words: " + countWhere(words, (w) => w.length > 3));
console.log("even numbers: " + countWhere(numbers, (n) => n % 2 === 0));