Skip to content

Commit

Permalink
✨ Add length function
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jun 17, 2021
1 parent 79851d6 commit f9ffce7
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 0 deletions.
20 changes: 20 additions & 0 deletions common/length.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright 2021-present the Core-fn authors. All rights reserved. MIT license.
/**
* Returns length property.
*
* @param val - Value with length property
* @returns The result of `val.length`
*
* @example
* ```ts
* length('hello') // 5
* length(['hello', 'world', 1]) // 3
* length({length: 5, text: 'hello'}) // 5
* ```
*
* @beta
*/
const length = <T extends { length: number }>(val: T): T["length"] =>
val.length;

export { length };
28 changes: 28 additions & 0 deletions common/length_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2021-present the Core-fn authors. All rights reserved. MIT license.
import { assertEquals, assertEqualsType } from "../dev_deps.ts";
import { length } from "./length.ts";

Deno.test("length", () => {
const table: [{ length: number } | string, number][] = [
["", 0],
[" ", 1],
[" ", 2],
["a", 1],
["ab", 2],
["hello", 5],
[[], 0],
[[""], 1],
[["", 0], 2],
[["", 0, "1"], 3],
[{ length: 3 }, 3],
];

table.forEach(([val, expected]) => {
assertEquals(length(val), expected, `length(${val}) -> ${expected}`);
});

assertEqualsType<number>(length(""));
assertEqualsType<number>(length([]));
assertEqualsType<number>(length({ length: 1 }));
assertEqualsType<1>(length({ length: 1 } as const));
});
2 changes: 2 additions & 0 deletions common/mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// Copyright 2021-present the Core-fn authors. All rights reserved. MIT license.
export { length } from "./length.ts";
1 change: 1 addition & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
// Copyright 2021-present the Core-fn authors. All rights reserved. MIT license.
export * from "./string/mod.ts";
export * from "./common/mod.ts";

0 comments on commit f9ffce7

Please sign in to comment.