JavaScript: Reducing the use of the For Loop

no for loops
  • aggregating a list objects into a single object
  • transforming a list of objects into a list of different objects
  • decreasing the size of a list
  • side effects, such as the mutation of the original list
  • potential multiple responsibilities in that bit of code

Reduce: The ‘new’ basis of list processing

const add2 = (a,b) => a + b// using the array method
const sumList = list => list.reduce(add2, 0)
// using a list processing library
const sumList = list => reduce(add2, 0, list)
// in usage
const total = sumList(list)
let total = 0 ;for(let i = 0; i < list.length; i++) {
total = total + list[i] ;
}
// ::  [a] -> a
const head = xs => xs[0]

// :: [a] -> [a]
const tail = xs => xs.slice(1)

// :: ( ((b,a) -> b), b, [a] ) -> b
const reduce = (f, agg, list) =>
(list.length == 0) ?
agg :
reduce(f, f(agg, head(list)), tail(list)) ;
// :: ( ((b,a) -> b), b, [a] ) -> b
const reduce = (f, agg, xs) => {
for(let i =0; i < xs.length; i++) {
agg = f(agg, xs[i])
}
return agg
}

Hindley-Milner

Beyond Reduce

Map, Filter, Find is really just Reduce “Snazzed Up”

// :: ([a], a) -> [a]
const append = (xs, x) => xs.concat([x])
// :: (a -> b) -> ([b], a) -> [b]
const transformingAppender = f =>
(agg, x) =>
append(agg, f(x))
// :: (a -> b) -> [a] -> [b]
const map = f => reduce(transformingAppender(f), [])
// :: (a -> Boolean) -> ([a], a) -> [a]
const conditionalAppender = f =>
(agg, x) =>
f(x) ?
append(agg, x) :
agg
// :: (a -> Boolean) -> [a] -> [a]
const filter = f => reduce(conditionalAppender(f), [])

Favor Readability over for-loop comfort

  1. Abelson & Sussman, Structure and Interpretation of Computer Programs, ISBN-13: 978–0262510875
  2. https://github.com/fantasyland/fantasy-land

--

--

--

A 25 year software industry veteran with a passion for functional programming, architecture, mentoring / team development, xp/agile and doing the right thing.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Managing Multiple Node.js Versions

Scala : headOption

What is Node.js?

Developing Unit Tests with Mocha

Better Array check with Array.isArray

Generating some next generation web components

Learning Angular as a React Developer — Apiumhub

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Todd Brown

Todd Brown

A 25 year software industry veteran with a passion for functional programming, architecture, mentoring / team development, xp/agile and doing the right thing.

More from Medium

Roman to Integer in Typescript (again :))

Packaging a Typescript library — Part 1

Get the First, Last and Middle Elements of an Array using JavaScript