Is there a "all" or "any" operator for boolean lists in typescript
Asked Answered
T

3

8

I want to write an if statement of the form

if (all entries in booleanList are true) {do something}

Just putting in the booleanList does the equivalent of .any()

I could not find an answer on the internet or in a typescript book. Thanks in advance for any help.

Timecard answered 19/2, 2020 at 14:1 Comment(0)
M
3

Sure, it's every:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

const list = [true, false, true];

const every = list.every(bool => bool === true); // false
// const every = list.every(bool => bool); // false
Myxomycete answered 19/2, 2020 at 14:7 Comment(3)
thank you I'm going to accept @Eras answer since he was the fastest.Timecard
@Eras was actually the slowest :DAmatol
for me it says 13 for him and 12 for the other 2Timecard
E
11

Typescript compiles to Javascript, so it doesn't have any features available at runtime that Javascript doesn't have. However, Javascript does have both every and some since ES5, so long as you pass an identity function:

arr.every(x => x) // all
arr.some(x => x)  // any

This kind of thing is unlikely to be documented in Typescript books specifically, because there would be no need to duplicate the contents of a Javascript book just to say that Typescript has those features too. If you want to know what functions are available in the standard library, you should consult a Javascript reference, such as the MDN Javascript reference.

Eras answered 19/2, 2020 at 14:8 Comment(0)
G
5

You could use the Array.prototype.every() function for that:

if(booleanList.every(val => val)){
 do something
}
Generality answered 19/2, 2020 at 14:6 Comment(2)
thank you I'm going to accept @Eras answer since he was the fastest.Timecard
if by fastest, you mean answered last, sure, but that's not what that word means. have my upvote, on account of being fasted.Concerted
M
3

Sure, it's every:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

const list = [true, false, true];

const every = list.every(bool => bool === true); // false
// const every = list.every(bool => bool); // false
Myxomycete answered 19/2, 2020 at 14:7 Comment(3)
thank you I'm going to accept @Eras answer since he was the fastest.Timecard
@Eras was actually the slowest :DAmatol
for me it says 13 for him and 12 for the other 2Timecard

© 2022 - 2024 — McMap. All rights reserved.