0.3.0 • Published 6 years ago

ts-object v0.3.0

Weekly downloads
3
License
ISC
Repository
github
Last release
6 years ago

Utility methods for working with plain js objects in TypeScript just like with arrays.

All functions can be used in two ways:

  • By passing all parameters, then TypeScript can correctly detect all types
  • By leaving last parameter for point free style programming. In many cases TypeScript can't correctly detect types and explicit generic parameters are required but it should work with pipe method

Installation

npm i ts-object

Usage

import {
  map,
  filter,
  reduce,
  some,
  every,
  mapToArray,
  keys,
  values,
} from "ts-object"

const obj = {
  a: 1,
  b: 2,
  c: 3,
}

const mappedObj = map((v, k) => (k === "b" ? v * 3 : v * 2), obj)
const mappedObj = map<typeof obj, number>(
  (v, k) => (k === "b" ? v * 3 : v * 2),
)(obj)

const filteredObj = filter((v, k) => v > 1 && k > "b", obj)
const filteredObj = filter<typeof obj>((v, k) => v > 1 && k > "b")(obj)

const reducedObj = reduce(
  (acc, v, k) => [...acc, { v, k }],
  [] as Array<{ v: number; k: string }>,
  obj,
)
const reducedObj = reduce<
  typeof obj,
  Array<{
    v: number
    k: string
  }>
>((acc, v, k) => [...acc, { v, k }], [])(obj)

const any = some((v, k) => v === 2 && k === "b", obj)
const any = some<typeof obj>((v, k) => v === 2 && k === "b")(obj)

const all = every((v, _k) => v > 0, obj)
const all = every<typeof obj>((v, _k) => v > 0)(obj)

const arr = mapToArray((v, k) => ({ v, k }), obj)
const arr = mapToArray<typeof obj, { k: string; v: number }>((v, k) => ({
  v,
  k,
}))(obj)

const keys = keys(obj)
const values = values(obj)

const arr = [{ v: 1, k: "a" }, { v: 2, k: "b" }, { v: 3, k: "c" }]

const obj = fromArray((x) => x.k, (x) => x.v, arr)
const obj = fromArray<typeof arr[0], number>((x) => x.k, (x) => x.v)(arr)
0.3.0

6 years ago

0.2.0

6 years ago

0.1.2

6 years ago

0.1.1

6 years ago

0.1.0

6 years ago

1.0.0

6 years ago