Skip to content

from.js

js
const from = iter => Array.from(iter)

const map = new Map()
map.set('a', 1)
map.set('b', 2)
map.set('c', 3)

from(map)
// [['a', 1], ['b', 2], ['c', 3]]

iterable.ts

ts
const from = iter => Array.from(iter)

export const map = (mapper, iterable) => {
  return from(iterable).map(mapper)
}

export const filter = (predicate, iterable) => {
  return from(iterable).filter(predicate)
}

export const join = (sep, iter) => from(iter).join(sep)

export const size = (iterable) => from(iterable).length

join.js

js
const join = (sep, iter) => Array.from(iter).join(sep)

join('&', ['a=1', 'c=CC', 'd=DD']) // a=1&c=CC&d=DD
join('&', new Set(['a=1', 'c=CC', 'd=DD'])) // a=1&c=CC&d=DD

recur1.js

js
const linkedList = arr => arr.reduceRight((a, b) => [b, a], [])

function concat(a, list) {
  return [a, list]
}

function map(fn, [head, tail]) {
  if (head === undefined) {
    return []
  }
  return concat(fn(head), map(fn, tail))
}

function filter(pred, [head, tail]) {
  if (head === undefined) {
    return []
  }
  if (pred(head)) {
    return concat(head, filter(pred, tail))
  } else {
    return filter(pred, tail)
  }
}

const xs = linkedList([0, 1, 2, 3])
const ys = map(n => n * 10, xs)
const zs = filter(n => n > 1, xs)

console.log(zs)

recur2.js

js
const linkedList = arr => arr.reduceRight((a, b) => [b, a], [])

function *concat(a, list) {
  yield [a, list]
}

function *map(fn, [head, tail]) {
  if (head === undefined) {
    yield []
  }
  yield* concat(fn(head), map(fn, tail))
}

function *filter(pred, [head, tail]) {
  if (head === undefined) {
    yield []
  }
  if (pred(head)) {
    yield concat(head, filter(pred, tail))
  } else {
    yield filter(pred, tail)
  }
}

const xs = linkedList([0, 1, 2, 3])
const ys = map(n => n * 10, xs)
const zs = filter(n => n > 1, xs)

console.log(ys.next())
console.log(ys.next())
console.log(ys.next())
console.log(ys.next())
console.log(ys.next())