takeIf and takeUnless
const number: number = Math.floor(Math.random() * 100);
const evenOrNull = number.takeIf(it => it % 2 == 0);
const oddOrNull = number.takeUnless(it => it % 2 == 0);
console.log(`even: ${evenOrNull}, odd: ${oddOrNull}`);const str = "Hello";
const caps = str.takeIf(it => it.length > 0)?.toUpperCase();
//const caps = str.takeIf(it => it.length > 0).toUpperCase() //compilation error
console.debug(caps);function displaySubstringPosition(input: string, sub: string) {
input.indexOf(sub)
.takeIf(it => it >= 0)
?.letIt(it => {
console.log(`The substring ${sub} is found in ${input}.`)
console.log(`Its start position is ${it}.`)
});
}
displaySubstringPosition("010000011", "11");
displaySubstringPosition("010000011", "12");
// Output:
// The substring 11 is found in 010000011.
// Its start position is 7.Last updated