How to use the reduce function from ramda

Find comprehensive JavaScript ramda.reduce code examples handpicked from public code repositorys.

152
153
154
155
156
157
158
159
160
    ]
  })

const valueOf = key => [search(key), 'value']

const fromPairs = R.reduce(
  (t, kv) => L.set(valueOf(kv[0]), kv[1], t),
  undefined
)
fork icon41
star icon901
watch icon29

+ 3 other calls in file

278
279
280
281
282
283
284
285
286
287
  store.clear();
}

projects = R.flatten(nestedProjects);

// const projectsByMonth = R.reduce(
//    (accum, project) => R.set(
//       dateLens(project),
//       R.view(dateLens(project), accum) ?
//         R.view(dateLens(project), accum).concat(project) :
fork icon6
star icon57
watch icon4

+ 3 other calls in file

96
97
98
99
100
101
102
103
104
105
const isString = (str) => str && typeof str === 'string'

const isNotEmpty = (str) => R.not(R.isEmpty(str))

const foldObject = (prop1, prop2, obj) =>
  R.reduce(
    (acc, t) => {
      acc[t[prop1]] = t[prop2]
      return acc
    },
fork icon3
star icon44
watch icon6

24
25
26
27
28
29
30
31
32
33

  return [...paths, ...nestedPaths]
}

const scopes = R.pipe(
  R.reduce(allPathCombinations, []),
  R.sort((a, b) => a.localeCompare(b)),
  R.uniq,
  R.addIndex(R.map)((name, index) => {
    return {
fork icon11
star icon40
watch icon12

9
10
11
12
13
14
15
16
17
18
19
20
21
  return buf.toString('hex')
}


const isObject = x => !R.isNil(x) && !Array.isArray(x) && typeof x === 'object'


const pipePromise_ = R.reduce((p, fn) => Promise.resolve(p).then(fn))


/**
 * Chains a sequence of calls and avoid callback hell
 * @sig (a -> Promise b, b -> Promise c, ...) -> (a -> Promise z)
fork icon2
star icon6
watch icon0

22
23
24
25
26
27
28
29
30
const loadSql = (location) => {
  const files = fs.readdirSync(location);
  const load = R.pipe(
    R.filter(sqlFile),
    R.map(join(location)),
    R.reduce(nameToContent, {})
  );
  return load(files);
};
fork icon1
star icon6
watch icon0

+ 3 other calls in file

165
166
167
168
169
170
171
172
173
174
message ${capitalize(name)} {
    ${mapIndexed((prop, idx) => {
      const propType = extractTypeFromProp(prop)
      const directives = __directives(prop)
      const isArrayType = isArray.includes(rootPropNames[idx])
      const isEnum = R.reduce((isAnEnum, e) => isAnEnum || R.equals(e.type, propType), false, generatedEnums)
      return `${tab(idx)}${isArrayType ? 'repeated ' : ''}${isEnum ? 'enums.' : ''}${propType} ${camelToSnakeCase(
        extractName(prop)
      )} = ${order(directives[extractName(prop)])};`
    }, rootStruct).join(EOL)}
fork icon3
star icon44
watch icon6

20
21
22
23
24
25
26
27
28
29
30
31
const pickFrameFields = (frame, obj) => compose(
  removePrefix(`${frame.def.from}!`),
  pickBy(compose(startsWith(`${frame.def.from}!`), nthArg(1)))
)(obj);


const makeHierarchy = reduce((result, item) => {
  const dataset = new Dataset(pickFrameFields(Dataset, item)).with({ lastEntity: item.lastEntity });
  const property = new Dataset.Property(pickFrameFields(Dataset.Property, item));


  return {
fork icon49
star icon43
watch icon9

18
19
20
21
22
23
24
25
26
27
28


    return marv.scanAsync(migrationPath, options)
      .then((migrations) => marv.migrateAsync(migrations, driver(options)));
  };


  return R.reduce((result, migrationConfig) => result.then(() => migrate(migrationConfig)),
    Promise.resolve(),
    migrationConfigs);
};
fork icon1
star icon6
watch icon0

38
39
40
41
42
43
44
45
46
47
48
49
  mergeWith((x, y) => flatten([x, y])),
  {}
)


const isolate = (scope, o) =>
  reduce((accumulator, key) => (o[key] ? assoc(key, o[key], accumulator) : accumulator), {}, scope)


const gatherPipes = (scope, configFile = rootConfigFile) =>
  reduce(
    (pipes, e) => {
fork icon2
star icon5
watch icon0

21
22
23
24
25
26
27
28
29
30
31
32
    toPairs(parentValue)
  )
)


const edit = curry((transform, paths, config) =>
  reduce((configStage, lens) => over(lens, c => transform(c), configStage), config, map(lensPath, paths))
)


const replace = curry((replacement, paths, config) =>
  reduce((configStage, path) => assocPath(path, replacement, configStage), config, paths)
fork icon2
star icon5
watch icon0

+ 7 other calls in file

198
199
200
201
202
203
204
205
206
207
  R.zipWith((k, v) => ({
    [k]: v.map((u) => u.loc),
  })),
  [R.keys, R.values]
),
R.reduce((a, b) => {
  const key = Object.keys(b)[0];
  return {
    ...a,
    [key]: b[key],
fork icon2
star icon5
watch icon0

65
66
67
68
69
70
71
72
73
74
75
//also observe all operation are functions and curry placeholder
// over engineered code
const sumUsingPipe = _.pipe(
    _.filter(_.compose(_.identical(1), _.modulo(_.__, 2))),
    _.map(_.converge(_.multiply, [_.identity, _.identity])), // dont try this at home
    _.reduce(_.add, 0)
)
console.log('sumUsingPipe=', sumUsingPipe(range1To100))



fork icon1
star icon2
watch icon0

128
129
130
131
132
133
134
135
136
137
138
139
140
};


exports.getHotelsByMinPrice = getHotelsByMinPrice;


var hotelsByKey = function hotelsByKey() {
  return (0, _reselect.createSelector)(getHotelsByPages(), R.reduce(R.mergeRight, {}));
};


exports.hotelsByKey = hotelsByKey;

fork icon0
star icon3
watch icon4

+ 41 other calls in file

68
69
70
71
72
73
74
75
76
77
78
    return R.sort(R.ascend(R.path(['offers', 0, 'price', currency])), prices);
  };
};


var convertPricesListToMap = function convertPricesListToMap(prices) {
  return R.reduce(function (acc, price) {
    return R.over(R.lensProp(price.hotelID), function (prevPrice) {
      return prevPrice ? R.over(R.lensProp('offers'), function (offers) {
        return R.concat(offers, price.offers);
      }, prevPrice) : price;
fork icon0
star icon3
watch icon0

23
24
25
26
27
28
29
30
31
32
33
34
const totalCostReducer = (acc, city) => {
	const { cost = 0 } = city;
	return acc + cost;
};


const totalCost = R.reduce(totalCostReducer, 0, cities);
const cityCount = R.length(cities);
// console.log(totalCost / cityCount);


const groupByPropReducer = (acc, city) => {
fork icon0
star icon1
watch icon0

64
65
66
67
68
69
70
71
72
73
74
  return R.pipe(
    R.converge(R.xprod, [
      R.pipe(R.prop(0), R.pipe(R.length, R.flip(R.subtract)(1)), R.range(1)),
      R.pipe(R.pipe(R.length, R.flip(R.subtract)(1)), R.range(1)),
    ]),
    R.reduce(R.useWith(R.max, [R.identity, getScenicScore(grid)]), -Infinity),
  )(grid)
}


module.exports = {
fork icon0
star icon1
watch icon0

37
38
39
40
41
42
43
44
45
46
47
48


const parseTreeFromCommands = R.pipe(
  R.split('$ '),
  R.tail,
  R.map(R.pipe(R.trim, R.split('\n'))),
  R.reduce(runCommand, { cwd: null, tree: {} }),
  R.prop('tree'),
)


const buildPathSizesFromTree = (tree, cwd = []) => {
fork icon0
star icon1
watch icon0

+ 5 other calls in file

15
16
17
18
19
20
21
22
23
24
25
    ),
  ),
)


const boardFromInput = R.converge(
  R.reduce((acc, row) => {
    for (const [from, to] of R.aperture(2, row)) {
      for (const pos of iterateStraightLines(from, to)) {
        acc[vec.key(pos)] = '#'
      }
fork icon0
star icon1
watch icon0

22
23
24
25
26
27
28
29
30
31
module.exports = function compose(...args) {
    if (R.filter(_isFunction, args).length < args.length) {
        throw new Error(`Invalid Arguments. Expected functions but got: ${R.map(R.type, args)}`);
    }
    return initialContext => {
        return R.reduce(
            (ctx, fn) => {
                if (_isPromise(ctx)) {
                    return ctx.then(ctxP => {
                        return run(ctxP, fn);
fork icon0
star icon1
watch icon0

Other functions in ramda

Sorted by popularity

function icon

ramda.clone is the most popular function in ramda (30311 examples)