Lesson 1 · Unit 04
Strategy
Pass the algorithm in
What you practise
- Swap the algorithm, pass a function, replace a type-code conditional, choose at run time
Try a question from this lesson
Pick one
The mode comes from a setting that the user can change while the app runs. What does this print?
pick = {"low": min, "high": max}
nums = [4, 9, 3]
def show(mode):
return pick[mode](nums)
print(show("low"), show("high"))const pick = {
low: Math.min,
high: Math.max,
};
const nums = [4, 9, 3];
function show(mode) {
return pick[mode](...nums);
}
console.log(show("low"), show("high"));type Agg = (...n: number[]) => number;
const pick: Record<string, Agg> = {
low: Math.min,
high: Math.max,
};
const nums = [4, 9, 3];
function show(mode: string) {
return pick[mode](...nums);
}
console.log(show("low"), show("high"));Correct answer
3 9
Why
The string picks a function out of the table at the moment of the call. Nothing in show says which algorithm runs: that is decided at run time, by data, and the same function gives two answers.
JavaScript note...nums spreads the array into separate arguments, which is what Math.min expects.
TypeScript note(...n: number[]) => number is the type of a function that takes any number of numbers.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Strategy
A strategy is an interchangeable piece of behaviour, handed to the code that needs it. That code knows only how to call it.
Where functions are values, a strategy is usually just a function: no interface and no class per algorithm. Reach for a class only when the strategy needs several methods.
Python notesorted, min and max all take a key function: strategies built into the standard library.
JavaScript notearray.sort(compare) takes its comparison rule as a function: a strategy built into the language.
TypeScript noteA function type is the interface here. A function with the wrong parameters or return type is rejected at compile time.
Concept
A strategy with settings
Some strategies need a setting of their own: how much off, which tax rate.
Write a function that takes the setting and returns the strategy. The outer call fixes the setting; the inner function is what gets passed around. A small class with one method does the same job in more lines.
def coupon(off):
def deal(cost):
return cost - off
return deal
ten_off = coupon(10)function coupon(off) {
return (cost) => cost - off;
}
const tenOff = coupon(10);function coupon(off: number) {
return (cost: number) => cost - off;
}
const tenOff = coupon(10);TypeScript noteThe return type is inferred as (cost: number) => number, so the result fits wherever a function of that shape is expected.
9 more exercises in the app
- 3× type the answer
- 1× fill the blanks
- 1× true or false
- 2× multiple choice
- 1× order the lines
- 1× match the pairs
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.