Skip to content

when(), sortAsc(), sortDesc() and sum() added to Arrays

Compare
Choose a tag to compare
@MZanggl MZanggl released this 16 Apr 13:38

when

Executes callback if first given value evaluates to true. Result will get transformed back into a flooent array.

// can be a boolean
given([]).when(true, str => str.append(1)) // [1]
given([]).when(false, str => str.append(1)) // []

// or a method
given([]).when(array => array.is([]), array => array.append('called')) // ['called']
given([]).when(array => array.is([1]), array => array.append('called')) // []

sum

Returns the sum of the array.

given([2, 2, 1]).sum() // 5

For arrays of objects:

Returns the sum of the given field/result of callback in the array.

  const users = [{ id: 1, points: 10 }, { id: 2, points: 10 }, { id: 3, points: 10 }]

  given(users).sum('points') // 30
  given(users).sum(user => user.points * 10) // 300

sortAsc / sortDesc

Sorts an array in their respective order and returns a new array.

given([3, 1, 2]).sortAsc() // [1, 2, 3]
given([3, 1, 2]).sortDesc() // [3, 2, 1]

const numbers = [{ val: 3 }, { val: 1 }, { val: 2 }]
given(numbers).sortAsc('val') // [{ val: 1 }, { val: 2 }, { val: 3 }]
given(numbers).sortDesc('val') // [{ val: 3 }, { val: 2 }, { val: 1 }]