diff --git a/index.js b/index.js index 7ac9021d..4c313d6d 100644 --- a/index.js +++ b/index.js @@ -3778,6 +3778,31 @@ S.pairs = def('pairs', {}, [$.StrMap(a), $.Array($.Pair($.String, a))], pairs); + //# fromPairs :: Foldable f => f (Pair String a) -> StrMap a + //. + //. Returns a string map containing the key–value pairs specified by the + //. given [Foldable][]. If a key appears in multiple pairs, the rightmost + //. pair takes precedence. + //. + //. ```javascript + //. > S.fromPairs([['a', 1], ['b', 2], ['c', 3]]) + //. {a: 1, b: 2, c: 3} + //. + //. > S.fromPairs([['x', 1], ['x', 2]]) + //. {x: 2} + //. ``` + function fromPairs(pairs) { + return Z.reduce(function(strMap, pair) { + strMap[pair[0]] = pair[1]; + return strMap; + }, {}, pairs); + } + S.fromPairs = + def('fromPairs', + {f: [Z.Foldable]}, + [f($.Pair($.String, a)), $.StrMap(a)], + fromPairs); + //. ### Number //# negate :: ValidNumber -> ValidNumber diff --git a/test/fromPairs.js b/test/fromPairs.js new file mode 100644 index 00000000..790075a3 --- /dev/null +++ b/test/fromPairs.js @@ -0,0 +1,19 @@ +'use strict'; + +var S = require('..'); + +var eq = require('./internal/eq'); + + +test('fromPairs', function() { + + eq(typeof S.fromPairs, 'function'); + eq(S.fromPairs.length, 1); + eq(S.fromPairs.toString(), 'fromPairs :: Foldable f => f (Pair String a) -> StrMap a'); + + eq(S.fromPairs([]), {}); + eq(S.fromPairs([['a', 1], ['b', 2], ['c', 3]]), {a: 1, b: 2, c: 3}); + eq(S.fromPairs({x: ['a', 1], y: ['b', 2], z: ['c', 3]}), {a: 1, b: 2, c: 3}); + eq(S.fromPairs([['x', 1], ['x', 2]]), {x: 2}); + +});