Skip to content

Commit

Permalink
improve ayakashi.join() type
Browse files Browse the repository at this point in the history
  • Loading branch information
zisismaras committed Aug 25, 2019
1 parent 16e3cdd commit ddc491f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
18 changes: 10 additions & 8 deletions __tests__/prelude/join.test.ts
Expand Up @@ -78,9 +78,10 @@ describe("join() tests", function() {
});
const result = await ayakashiInstance.extract("myLinkProp");
expect(result).toEqual(["link1", "link2", "link3"]);
expect(ayakashiInstance.join({
const joined = ayakashiInstance.join({
text: result
})).toEqual([{
});
expect(joined).toEqual([{
text: "link1"
}, {
text: "link2"
Expand All @@ -102,18 +103,19 @@ describe("join() tests", function() {
});
const result = await ayakashiInstance.extract("myLinkProp");
expect(result).toEqual(["link1", "link2", "link3"]);
expect(ayakashiInstance.join({
const joined = ayakashiInstance.join({
text: result,
constant: "hello"
})).toEqual([{
constant: 5
});
expect(joined).toEqual([{
text: "link1",
constant: "hello"
constant: 5
}, {
text: "link2",
constant: "hello"
constant: 5
}, {
text: "link3",
constant: "hello"
constant: 5
}]);
await ayakashiInstance.__connection.release();
});
Expand Down
10 changes: 7 additions & 3 deletions src/prelude/actions/meta.ts
Expand Up @@ -98,9 +98,11 @@ ayakashi.registerExtractor("id", function() {
* Groups together multiple sets of related data.
* Learn more here: https://ayakashi.io/docs/guide/data-extraction.html#grouping-extracted-data
*/
join: (obj: {[key: string]: unknown}) => {[key: string]: unknown}[];
join: <T>(obj: T) => {[P in keyof T]: valueof<T[P]>}[];
}

type valueof<T> = T extends (infer U)[] ? U : T;

export function attachMetaActions(
ayakashiInstance: IAyakashiInstance | IRenderlessAyakashiInstance,
connection: IConnection
Expand Down Expand Up @@ -208,6 +210,7 @@ export function attachMetaActions(
};
};

//@ts-ignore
ayakashiInstance.join = function(obj) {
if (!obj || typeof obj !== "object" || Object.keys(obj).length === 0) {
throw new Error("Invalid object");
Expand Down Expand Up @@ -238,7 +241,7 @@ export function attachMetaActions(
}
//check if we only have non-array values
if (max === 0) {
let j: {[key: string]: unknown} = {};
let j = {};
if (nonArrays.length > 0) {
for (const nonArray of nonArrays) {
j = {...j, ...nonArray};
Expand All @@ -250,9 +253,10 @@ export function attachMetaActions(
//create the joined value
const joined = [];
for (let i = 0; i < max; i += 1) {
let j: {[key: string]: unknown} = {};
let j = {};
for (const [key, val] of Object.entries(obj)) {
if (Array.isArray(val)) {
//@ts-ignore
j[key] = val[i];
}
}
Expand Down

0 comments on commit ddc491f

Please sign in to comment.