Add group function (#3175)
This commit is contained in:
parent
276edd7cc2
commit
500fc47618
|
@ -15,6 +15,9 @@ import { TextElementSearch } from './elements/search';
|
||||||
import { TextElementTitle } from './elements/title';
|
import { TextElementTitle } from './elements/title';
|
||||||
import { TextElementUrl } from './elements/url';
|
import { TextElementUrl } from './elements/url';
|
||||||
import { TextElementMotion } from './elements/motion';
|
import { TextElementMotion } from './elements/motion';
|
||||||
|
import { groupOn } from '../../prelude/array';
|
||||||
|
import * as A from '../../prelude/array';
|
||||||
|
import * as S from '../../prelude/string';
|
||||||
|
|
||||||
const elements = [
|
const elements = [
|
||||||
require('./elements/big'),
|
require('./elements/big'),
|
||||||
|
@ -89,16 +92,10 @@ export default (source: string): TextElement[] => {
|
||||||
i++;
|
i++;
|
||||||
}
|
}
|
||||||
|
|
||||||
// テキストを纏める
|
const combineText = (es: TextElement[]): TextElement =>
|
||||||
return tokens.reduce((a, b) => {
|
({ type: 'text', content: S.concat(es.map(e => e.content)) });
|
||||||
if (a.length && a[a.length - 1].type == 'text' && b.type == 'text') {
|
|
||||||
const tail = a.pop();
|
return A.concat(groupOn(x => x.type, tokens).map(es =>
|
||||||
return a.concat({
|
es[0].type === 'text' ? [combineText(es)] : es
|
||||||
type: 'text',
|
));
|
||||||
content: tail.content + b.content
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
return a.concat(b);
|
|
||||||
}
|
|
||||||
}, [] as TextElement[]);
|
|
||||||
};
|
};
|
||||||
|
|
|
@ -29,3 +29,19 @@ export function unique<T>(xs: T[]): T[] {
|
||||||
export function sum(xs: number[]): number {
|
export function sum(xs: number[]): number {
|
||||||
return xs.reduce((a, b) => a + b, 0);
|
return xs.reduce((a, b) => a + b, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function groupBy<T>(f: (x: T, y: T) => boolean, xs: T[]): T[][] {
|
||||||
|
const groups = [] as T[][];
|
||||||
|
for (const x of xs) {
|
||||||
|
if (groups.length !== 0 && f(groups[groups.length - 1][0], x)) {
|
||||||
|
groups[groups.length - 1].push(x);
|
||||||
|
} else {
|
||||||
|
groups.push([x]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function groupOn<T, S>(f: (x: T) => S, xs: T[]): T[][] {
|
||||||
|
return groupBy((a, b) => f(a) === f(b), xs);
|
||||||
|
}
|
||||||
|
|
|
@ -1,3 +1,7 @@
|
||||||
|
export function concat(xs: string[]): string {
|
||||||
|
return xs.reduce((a, b) => a + b, "");
|
||||||
|
}
|
||||||
|
|
||||||
export function capitalize(s: string): string {
|
export function capitalize(s: string): string {
|
||||||
return toUpperCase(s.charAt(0)) + toLowerCase(s.slice(1));
|
return toUpperCase(s.charAt(0)) + toLowerCase(s.slice(1));
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue