- Source:
Into can be used to turn sequences back into other types.
into is the inverse of iter(), meaning that taking the result
of iter() and calling into(), yields the original value.
So in a purely functional language, into(iter(v)) would be a
no-op; since we are in javascript, this essentially implements
a poor mans shallow copy for some types
const shallowcopy = (v) => into(v, v.constructor);
Interface
`(T: Type/Function, v: Sequence) => r: T
Laws
into(v, type(v)) <=> shallowclone(v)
Specialization notes
String: Uses toString() on each value from the sequence and concatenates them into one string... Object: Expects key/value pairs; the keys must be strings; sequences containing the same key multiple times and sequences with bad key/value pairs are considered to be undefined behaviour. The key/value pairs may be sequences themselves. Map: Same rules as for object. Set: Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
Examples
Practical uses of into include converting between types; e.g:
const { into } = require('ferrum');
into({foo: 42, bar: 23}, Map) // Map { 'foo' => 42, 'bar' }
into(["foo", " bar"], String) // "foo bar"
into([1,1,2,3,4,2], Set) // Set(1,2,3,4)
Into is also useful to transform values using the functions in this class:
const { into, filter } = require('ferrum');
// Remove odd numbers from a set
const st = new Set([1,1,2,2,3,4,5]);
into(filter(st, n => n % 2 === 0), Set) // Set(2,4)
// Remove a key/value pair from an object
const obj = {foo: 42, bar: 5};
into(filter(obj, ([k, v]) => k !== 'foo'), Object)
// yields {bar: 5}
It can be even used for more complex use cases:
const { concat, into } = require('ferrum');
// Merge multiple key/value containers into one sequence:
const seq = concat([[99, 42]], new Map([[true, 23]]), {bar: 13});
into(seq, Map) // Map( 99 => 42, true => 23, bar => 13 )