Skip to content

smartlyio/safe-navigation

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

78ef8d5 · May 3, 2024
Mar 20, 2023
Sep 25, 2019
Jun 18, 2020
Jun 30, 2020
May 13, 2020
May 13, 2020
Jun 30, 2020
Jun 6, 2022
Apr 13, 2023
Mar 20, 2019
May 13, 2020
Mar 20, 2019
Jun 18, 2020
Sep 6, 2019
Mar 29, 2023
May 3, 2024
May 13, 2020
Aug 26, 2021
Mar 20, 2023

Repository files navigation

safe-navigation

type(script) and null safe navigation in json objects

get .$

Returns the value or undefined if any value on the path to it is undefined

// yarn ts-node examples/getter.ts
import safe from '../index';
import * as assert from 'assert';

interface A {
  a?: { b?: string };
}
const o: A = { a: { b: 'x' } };
assert(safe(o).a.b.$ === 'x');

The optional chaining also takes into account union types.

// yarn ts-node examples/unions.ts
import safe from '../index';
import * as assert from 'assert';

type A = { a: number } | { b: string };
const o: A = { a: 1 };
assert(safe(o).a.$ === 1);

set value .$set

Returns a new object with the target set to value if the path to value exists

// yarn ts-node examples/set.ts
import safe from '../index';
import * as assert from 'assert';

interface A {
  a?: { b?: string };
}
const o: A = { a: { b: 'old' } };
const newValue: A = safe(o).a.b.$set('new');
assert(safe(newValue).a.b.$ === 'new');

map value .$map

Maps the value at end of the path

// yarn ts-node examples/map.ts
import safe from '../index';
import * as assert from 'assert';

interface A {
  a?: { b?: string };
}
const o: A = { a: { b: 'old' } };
const newValue: A = safe(o).a.b.$map((n: any) => n + ' to new');
assert(safe(newValue).a.b.$ === 'old to new');

map with promises .$pmap

Returns a new object with the target mapped using a promise returning map function

// yarn ts-node examples/pmap.ts
import safe from '../index';
import * as assert from 'assert';

interface A {
  a?: { b?: string };
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
(async function () {
  const o: A = { a: { b: 'x' } };
  const result = await safe(o).a.b.$pmap(async value => 'got ' + value);
  assert(safe(o).a.b.$ === 'x');
  assert(safe(result).a.b.$ === 'got x');
})();

About

type and null safe navigation in json objects

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published