Skip to content

Commit

Permalink
feat(map): add map function
Browse files Browse the repository at this point in the history
  • Loading branch information
djcsdy committed Oct 11, 2019
1 parent 7c34ec9 commit 5c7279f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
6 changes: 5 additions & 1 deletion index.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
import test from "ava";
import {map} from "./index";

test("placeholder test", t => t.true(true));
test("map", t => {
t.deepEqual(map({a: 1, b: 2}, value => value + 1), {a: 2, b: 3});
t.deepEqual(map({a: 1, b: 2}, (value, key) => (value * 2) + key), {a: "2a", b: "4b"});
});
11 changes: 11 additions & 0 deletions index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,23 @@ export function copy<T>(dictionary: ReadonlyDictionary<T>): Dictionary<T> {
return {...dictionary};
}

// tslint:disable-next-line:no-unbound-method
export const keys: <T>(dictionary: ReadonlyDictionary<T>) => string[] = Object.keys;

// tslint:disable-next-line:no-unbound-method
export const values: <T>(dictionary: ReadonlyDictionary<T>) => T[] = Object.values;

// tslint:disable-next-line:no-unbound-method
export const entries: <T>(dictionary: ReadonlyDictionary<T>) => Array<[string, T]> = Object.entries;

export function empty<T>(dictionary: ReadonlyDictionary<T>): boolean {
return keys(dictionary).length === 0;
}

export function map<T, U>(dictionary: ReadonlyDictionary<T>, f: (value: T, key: string) => U): Dictionary<U> {
const result: Dictionary<U> = {};
for (const [key, value] of entries(dictionary)) {
result[key] = f(value, key);
}
return result;
}

0 comments on commit 5c7279f

Please sign in to comment.