Clojure's core/merge_with in TypeScript

How to use

Install via yarn add locutus and import: import { merge_with } from 'locutus/clojure/core/merge_with'.

Or with CommonJS: const { merge_with } = require('locutus/clojure/core/merge_with')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1merge_with((a, b) => Number(a) + Number(b), {a: 1}, {a: 2, b: 3}){a: 3, b: 3}
2merge_with((a, b) => [a, b].join(','), {x: 'a'}, {x: 'b'}, {y: 'c'}){x: 'a,b', y: 'c'}
3merge_with((a, b) => b, {}){}

Notes

  • Merges maps and combines colliding values with combiner, like Clojure merge-with.

Here's what our current TypeScript equivalent to Clojure's core/merge_with looks like.

type MergeRecord = { [key: string]: unknown }
type MergeCombiner = (left: unknown, right: unknown, key: string) => unknown

export function merge_with(combiner: MergeCombiner, ...maps: unknown[]): MergeRecord {
// discuss at: https://locutus.io/clojure/merge_with/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Merges maps and combines colliding values with combiner, like Clojure merge-with.
// example 1: merge_with((a, b) => Number(a) + Number(b), {a: 1}, {a: 2, b: 3})
// returns 1: {a: 3, b: 3}
// example 2: merge_with((a, b) => [a, b].join(','), {x: 'a'}, {x: 'b'}, {y: 'c'})
// returns 2: {x: 'a,b', y: 'c'}
// example 3: merge_with((a, b) => b, {})
// returns 3: {}

if (typeof combiner !== 'function') {
throw new TypeError('merge_with(): combiner must be a function')
}

const out: MergeRecord = {}

for (const map of maps) {
if (!map || typeof map !== 'object' || Array.isArray(map)) {
continue
}

for (const [key, value] of Object.entries(map as MergeRecord)) {
if (Object.hasOwn(out, key)) {
out[key] = combiner(out[key], value, key)
} else {
out[key] = value
}
}
}

return out
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 14 Clojure functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

  • Get inspiration from ClojureDocs.
  • Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Clojure core functions


Star