{ "version": 3, "sources": ["../shared/ajax.ts", "../shared/dom.ts", "../shared/router.ts", "ts/bq.ts", "ts/api.ts", "../shared/svg.ts", "../shared/graph.ts", "../shared/vertbars.ts", "../shared/single_number.ts", "../shared/display_chart.ts", "../shared/linegraph.ts", "ts/display.ts", "../shared/loading.ts", "../shared/overlay.ts", "../shared/date_format.ts", "ts/viz_svg.ts", "ts/table_picker.ts", "../shared/menu.ts", "../shared/input_callback.ts", "../shared/constants.ts", "../classic/ts/constants.ts", "../shared/date_locale.ts", "../shared/date_picker.ts", "ts/editor_page.ts", "ts/editor.ts", "../shared/dropdown.ts", "ts/teams.ts", "ts/upload.ts", "ts/auth.ts", "ts/settings.ts", "ts/files_page.ts", "ts/page.ts", "ts/index_page.ts", "ts/app.ts", "node_modules/uuid/lib/rng-browser.js", "node_modules/uuid/lib/bytesToUuid.js", "node_modules/uuid/v1.js", "node_modules/uuid/v4.js", "node_modules/uuid/index.js", "node_modules/lodash/lodash.js", "node_modules/codemirror/lib/codemirror.js", "node_modules/codemirror/mode/sql/sql.js"], "sourcesContent": ["\nexport interface AjaxCallback {\n (data: any): void;\n}\n\nexport interface AjaxFailureCallback {\n (status: number, data: any): void;\n}\n\ninterface AjaxParams {\n method: string;\n path: string;\n cb: AjaxCallback;\n body?: FormData | Object;\n failure_cb?: AjaxFailureCallback;\n}\n\nexport class Ajax {\n\n static csrf: string | null = null;\n\n static getCSRFToken(doc: Document): string | null {\n if (!doc.head) {\n return null;\n }\n const meta = doc.head.querySelector('meta[name=\"csrf.token\"]') as HTMLMetaElement;\n if (meta !== null) {\n return meta.content;\n }\n return null;\n }\n\n static setCSRFHeader(r: XMLHttpRequest) {\n if (!Ajax.csrf) {\n Ajax.csrf = Ajax.getCSRFToken(document);\n }\n if (Ajax.csrf) {\n r.setRequestHeader(\"X-CSRF-Token\", Ajax.csrf);\n }\n }\n\n static get(path: string, cb: AjaxCallback, failure_cb?: AjaxFailureCallback) {\n Ajax.perform({ method: \"GET\", path: path, cb: cb, body: undefined, failure_cb: failure_cb });\n }\n\n static put(path: string, cb: AjaxCallback, body?: FormData | Object, failure_cb?: AjaxFailureCallback) {\n Ajax.perform({ method: \"PUT\", path: path, cb: cb, body: body, failure_cb: failure_cb });\n }\n\n static post(path: string, cb: AjaxCallback, body?: FormData | Object, failure_cb?: AjaxFailureCallback) {\n Ajax.perform({ method: \"POST\", path: path, cb: cb, body: body, failure_cb: failure_cb });\n }\n\n static delete(path: string, cb: AjaxCallback, failure_cb?: AjaxFailureCallback) {\n Ajax.perform({ method: \"DELETE\", path: path, cb: cb, body: undefined, failure_cb: failure_cb });\n }\n\n static perform(params: AjaxParams): void {\n const request = new XMLHttpRequest();\n request.open(params.method, params.path, true);\n Ajax.setCSRFHeader(request);\n\n let retry_count = 0;\n\n request.onload = function () {\n let ct = request.getResponseHeader(\"content-type\");\n const json = ct && ct.indexOf('json') > -1;\n let data = request.responseText;\n if (json) {\n try {\n data = JSON.parse(request.responseText);\n } catch (error) {\n // no-op\n }\n }\n if (request.status >= 200 && request.status < 400) {\n params.cb(data);\n } else if (params.failure_cb !== undefined) {\n const fail_cb = params.failure_cb;\n if (request.status === 403 && retry_count < 2) {\n retry_count++;\n console.log(\"403, updating csrf\");\n const r = new XMLHttpRequest();\n r.open(\"GET\", \"/\", true);\n\n // reset the token on load and retry the request\n r.onload = function () {\n try {\n const p = new DOMParser();\n const doc = p.parseFromString(r.responseText, \"text/html\");\n Ajax.csrf = Ajax.getCSRFToken(doc);\n send();\n } catch (ex) {\n console.log(ex);\n }\n }\n\n // just call the original fail cb on error\n r.onerror = function () {\n fail_cb(request.status, data);\n }\n r.send();\n } else {\n fail_cb(request.status, data);\n }\n }\n };\n\n request.onerror = function () {\n console.log(request.status, request);\n if (params.failure_cb !== undefined) {\n params.failure_cb(request.status, request.responseText);\n }\n };\n\n const send = function () {\n if (params.body instanceof FormData) {\n request.send(params.body);\n } else if (params.body instanceof Object) {\n request.setRequestHeader(\"Content-Type\", \"application/json\");\n request.send(JSON.stringify(params.body));\n } else {\n request.send();\n }\n }\n send();\n }\n}", "export function update(id: string, child: any) {\n const el = document.getElementById(id);\n if (!el || el === undefined) {\n return;\n }\n while (el.lastChild) {\n el.removeChild(el.lastChild);\n }\n el.appendChild(child);\n}\n\nexport function div(...node_class: string[]): HTMLDivElement {\n const d = document.createElement(\"div\");\n d.classList.add(...node_class);\n return d;\n}\n\nexport function span(...node_class: string[]): HTMLSpanElement {\n const s = document.createElement(\"span\");\n s.classList.add(...node_class);\n return s;\n}\n\nexport function anchor(...node_class: string[]): HTMLAnchorElement {\n const a = document.createElement(\"a\");\n a.classList.add(...node_class);\n return a;\n}\n\nexport function input(...node_class: string[]): HTMLInputElement {\n const i = document.createElement(\"input\");\n i.setAttribute(\"type\", \"text\");\n i.classList.add(...node_class);\n return i;\n}\n\nexport function textarea(...node_class: string[]): HTMLTextAreaElement {\n const el = document.createElement(\"textarea\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function inputSubmit(...node_class: string[]): HTMLInputElement {\n const i = input(...node_class);\n i.setAttribute(\"type\", \"submit\");\n return i;\n}\n\nexport function inputButton(...node_class: string[]): HTMLInputElement {\n const i = input(...node_class);\n i.setAttribute(\"type\", \"button\");\n return i;\n}\n\nexport function form(...node_class: string[]): HTMLFormElement {\n const f = document.createElement(\"form\");\n f.classList.add(...node_class);\n return f;\n}\n\nexport function h1(...node_class: string[]): HTMLHeadingElement {\n const el = document.createElement(\"h1\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function h2(...node_class: string[]): HTMLHeadingElement {\n const el = document.createElement(\"h2\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function p(...node_class: string[]): HTMLParagraphElement {\n const el = document.createElement(\"p\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function button(...node_class: string[]): HTMLButtonElement {\n const el = document.createElement(\"button\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function table(...node_class: string[]): HTMLTableElement {\n const el = document.createElement(\"table\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function tablehead(...node_class: string[]): HTMLTableSectionElement {\n const el = document.createElement(\"thead\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function tablerow(...node_class: string[]): HTMLTableRowElement {\n const el = document.createElement(\"tr\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function tabledata(...node_class: string[]): HTMLTableDataCellElement {\n const el = document.createElement(\"td\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function tableheadcell(...node_class: string[]): HTMLTableHeaderCellElement {\n const el = document.createElement(\"th\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function br(...node_class: string[]): HTMLBRElement {\n const el = document.createElement(\"br\");\n el.classList.add(...node_class);\n return el;\n}\n\nexport function textnode(text: string): Text {\n return document.createTextNode(text);\n}", "interface Route {\n regex?: RegExp;\n path: string;\n keys: string[];\n func: Function;\n}\n\nexport class Router {\n static_routes: Route[] = [];\n regex_routes: Route[] = [];\n not_found_route: Route | undefined;\n before_match: Function | undefined;\n\n add_not_found_route(callback: Function) {\n const r: Route = {\n path: \"\",\n regex: undefined,\n keys: [],\n func: callback,\n };\n this.not_found_route = r;\n }\n\n add(path: string, callback: Function) {\n const r: Route = {\n path: path,\n regex: undefined,\n keys: [],\n func: callback,\n };\n const trim_path = this.trim_leading_slash(path);\n if (trim_path.indexOf(\":\") !== -1) {\n const parts = trim_path.split(\"/\");\n const re_parts: string[] = [];\n parts.forEach(p => {\n if (p.indexOf(\":\") !== -1) {\n r.keys.push(p.replace(\":\", \"\"));\n re_parts.push(\".+\");\n } else {\n r.keys.push(\"\");\n re_parts.push(p);\n }\n });\n r.regex = new RegExp(re_parts.join(\"/\"), \"i\");\n }\n if (r.regex !== undefined) {\n this.regex_routes.push(r);\n } else {\n this.static_routes.push(r);\n }\n this.static_routes.sort(function (a, b) {\n return b.path.length - a.path.length;\n });\n this.regex_routes.sort(function (a, b) {\n return b.path.length - a.path.length;\n });\n }\n\n match() {\n if (this.before_match !== undefined) {\n this.before_match();\n }\n let path = window.location.pathname;\n if (path.charAt(path.length - 1) === \"/\" && path.length > 1) {\n path = path.slice(0, -1);\n }\n\n let matched = false;\n this.static_routes.some(route => {\n if (route.path === path) {\n matched = true;\n route.func.call(this);\n return true;\n }\n })\n if (matched) {\n return;\n }\n\n this.regex_routes.some(route => {\n let route_match = false;\n // need to check the number of \"/\" characters\n // to prevent, for example, \"/:username\" from matching \"/one/two\"\n if (route.regex) {\n const path_slash = path.split(\"/\").length;\n const route_slash = route.path.split(\"/\").length;\n route_match = route.regex.test(path) && path_slash === route_slash;\n }\n if (route_match) {\n matched = true;\n const args: string[] = [];\n if (route.keys.length) {\n const trim_path = this.trim_leading_slash(path);\n const parts = trim_path.split(\"/\");\n for (let i = 0; i < parts.length; i++) {\n const p = parts[i];\n if (route.keys[i] !== \"\") {\n args.push(p);\n }\n }\n }\n route.func.call(this, ...args);\n return true;\n }\n });\n if (!matched && this.not_found_route !== undefined) {\n this.not_found_route.func.call(this, path);\n }\n }\n\n private trim_leading_slash(p: string): string {\n let t = p;\n if (t.charAt(0) === \"/\") {\n t = t.substr(1);\n }\n return t;\n }\n}", "import { BQData } from \"./app\";\nimport { ApiBQResponse, ApiErrorResponse, ApiBQQuery, ApiBQTable } from \"./api_data\";\nimport { Ajax } from \"../../shared/ajax\";\nimport { cloneDeep } from 'lodash';\nimport { Display, FilterConnection } from \"./display\";\nimport { Editor } from \"./editor\";\nconst indent = \" \";\n\nexport class BQ {\n\n static skip_col(col: BQData): boolean {\n return (col.pivoted && !BQ.date_col(col.column_type)) || col.hidden;\n }\n\n static date_col(column_type: string): boolean {\n const date = column_type.indexOf(\"DATE\") != -1;\n const timestamp = column_type.indexOf(\"TIMESTAMP\") != -1;\n return date || timestamp;\n }\n\n static numeric_col(column_type: string): boolean {\n const float = column_type.indexOf(\"FLOAT\") != -1;\n const int = column_type.indexOf(\"INT\") != -1;\n return float || int;\n }\n\n static field_name(str: string): string {\n let clean = str.replace(/-/g, \"_\");\n clean = clean.replace(/ /g, \"_\");\n clean = clean.replace(/[^a-zA-Z0-9_]+/g, \"\");\n return \"f_\" + clean;\n }\n\n static date_extract(facet: string): string {\n switch (facet) {\n case \"Day Of Week\":\n return \"DAYOFWEEK\";\n\n case \"Month Of Year\":\n return \"MONTH\";\n\n default:\n return \"QUARTER\";\n }\n }\n\n static date_pivot_number(value: string): number {\n switch (value) {\n case \"Sunday\":\n return 1;\n\n case \"Monday\":\n return 2;\n\n case \"Tuesday\":\n return 3;\n\n case \"Wednesday\":\n return 4;\n\n case \"Thursday\":\n return 5;\n\n case \"Friday\":\n return 6;\n\n case \"Saturday\":\n return 7;\n }\n return 0;\n }\n\n static col_agg(col: BQData): string {\n let op = \"SUM\";\n if (col.operation) {\n op = col.operation;\n }\n return op.toUpperCase() + \"(\" + col.column_name + \") as \" + col.column_name;\n }\n\n static pivot_select(viz: Display, col: BQData, target: string, column_name: string): string {\n if (!col.pivot) {\n return \"\";\n }\n const select = function (query: string): string {\n if (viz.group_by) {\n query = \"SUM(\" + query + \")\";\n }\n query = query + \" AS \" + column_name;\n return query;\n }\n\n let s = \"\";\n if (col.column_type === \"STRING\") {\n s = \"IF (\" + col.column_name + \"='\" + col.pivot + \"', \" + target + \", 0)\";\n s = select(s);\n } else if (BQ.date_col(col.column_type) && col.pivot_facet) {\n const extract = BQ.date_extract(col.pivot_facet);\n const compare = BQ.date_pivot_number(col.pivot);\n s = \"IF (EXTRACT(\" + extract + \" FROM \" + col.column_name + \")=\" + compare + \", \" + target + \", 0)\";\n s = select(s);\n }\n return s;\n }\n\n static date_where(f: FilterConnection): string[] {\n let where_strs: string[] = [];\n switch (f.date_mode) {\n case Editor.date_recent.value:\n {\n const date_part = f.date_recent_interval === \"ISOWeek\" ? \" Week\" : f.date_recent_interval;\n let extract = \"DATE(\" + f.column + \")\";\n let sub = \"DATE_SUB\";\n let current = \"CURRENT_DATE()\";\n if (date_part === \"Hour\") {\n extract = f.column;\n sub = \"TIMESTAMP_SUB\"\n current = \"CURRENT_TIMESTAMP()\"\n }\n const s = extract + \" >= \" + sub + \"(\" + current + \", INTERVAL \" + f.date_recent_count + \" \" + date_part + \")\";\n where_strs.push(s);\n }\n\n break;\n\n case Editor.date_current.value:\n {\n const s = \"DATE(\" + f.column + \")\" + \" >= \" + \"DATE_TRUNC(CURRENT_DATE(),\" + f.date_current_interval + \")\";\n where_strs.push(s);\n }\n\n default: // custom range\n {\n if (f.date_min) {\n const s = \"DATE(\" + f.column + \")\" + \" >= '\" + f.date_min + \"'\";\n where_strs.push(s);\n }\n if (f.date_max) {\n const s = \"DATE(\" + f.column + \")\" + \" < '\" + f.date_max + \"'\";\n where_strs.push(s);\n }\n }\n break;\n }\n return where_strs;\n }\n\n static text_where(f: FilterConnection): string[] {\n let where_strs: string[] = [];\n const q = f.text_query ? f.text_query : \"\";\n const op = f.text_mode === Editor.text_match.value ? \"=\" : \"<>\";\n const s = f.column + \" \" + op + \" '\" + q + \"'\";\n where_strs.push(s);\n return where_strs;\n }\n\n static where(viz: Display): string {\n let where_strs: string[] = [];\n for (const f of viz.filters) {\n let col: BQData | null = null;\n for (const c of viz.selected_columns) {\n if (c.data.column_name === f.column) {\n col = c.data;\n break;\n }\n }\n if (col) {\n if (BQ.date_col(col.column_type)) {\n where_strs = where_strs.concat(BQ.date_where(f));\n } else if (col.column_type === \"STRING\") {\n where_strs = where_strs.concat(BQ.text_where(f));\n }\n }\n }\n if (where_strs.length > 0) {\n return \"WHERE\\n\" + indent + where_strs.join(\"\\n\" + indent + \"AND \") + \"\\n\";\n } else {\n return \"\";\n }\n }\n\n static build_query(viz: Display): string {\n let s = \"\";\n\n if (viz.query_columns.length == 0) {\n return s;\n }\n\n let default_sort_col: string | null = null;\n for (const col of viz.query_columns) {\n if (BQ.date_col(col.column_type)) {\n default_sort_col = col.column_name;\n break;\n }\n }\n\n let has_agg = false;\n for (const sel of viz.query_columns) {\n if (sel.operation) {\n has_agg = true;\n }\n }\n\n const query_has_group_or_agg = viz.group_by || has_agg;\n let use_group_by = false;\n\n let select_cols: string[] = [];\n let select_col_names: string[] = [];\n\n for (const sel of viz.query_columns) {\n // skip pivoted columns (original pivot column), and hidden\n if (BQ.skip_col(sel)) {\n continue;\n }\n\n if (sel.column_type === \"count\") {\n let target = \"*\";\n let as = \"Count\";\n if (viz.count_target) {\n target = \"DISTINCT \" + viz.count_target;\n as += \"_\" + viz.count_target;\n }\n const c = \"COUNT(\" + target + \") as \" + as;\n select_cols.push(c);\n continue;\n }\n\n let col = sel.column_name;\n let col_name = sel.column_name;\n if (sel.operation) {\n col = BQ.col_agg(sel);\n }\n if (query_has_group_or_agg) {\n if (sel.column_name === viz.group_by) {\n // only date grouping currently\n if (BQ.date_col(sel.column_type)) {\n use_group_by = true;\n let c = col;\n if (sel.column_type == \"TIMESTAMP\") {\n c = \"DATE(\" + c + \")\";\n }\n col = \"DATE_TRUNC(\" + c + \", \" + viz.group_by_interval + \") as \" + sel.column_name;\n }\n } else {\n if (sel.column_type === \"STRING\") {\n col = \"ARRAY_AGG(\" + sel.column_name + \") as \" + sel.column_name;\n } else if (BQ.date_col(sel.column_type)) {\n col = \"ANY_VALUE(\" + sel.column_name + \") as \" + sel.column_name;\n } else {\n col = BQ.col_agg(sel);\n }\n }\n }\n if (sel.pivot) {\n let val = BQ.field_name(sel.pivot);\n let target = \"1\"\n if (sel.pivot_target) {\n target = sel.pivot_target\n val = val + \"_\" + target\n }\n col_name = val;\n col = BQ.pivot_select(viz, sel, target, col_name);\n }\n select_cols.push(col);\n select_col_names.push(col_name);\n }\n\n if (!default_sort_col && select_col_names.length > 0) {\n default_sort_col = select_col_names[0];\n }\n\n let table = \"\";\n if (viz.selected_table) {\n table = viz.selected_table.table.dataset_id + \".\" + viz.selected_table.table.id;\n }\n\n s = \"SELECT\\n\";\n s += indent + select_cols.join(\",\\n\" + indent) + \"\\n\"\n s += \"FROM\\n\";\n s += indent + table + \"\\n\"\n\n if (viz.filters.length > 0) {\n s += BQ.where(viz);\n }\n\n if (viz.group_by && use_group_by) {\n s += \"GROUP BY\\n\" + indent + viz.group_by + \"\\n\";\n }\n if (viz.sort) {\n let sort_col_included = false;\n for (const col of viz.query_columns) {\n if (col.column_name === viz.sort) {\n sort_col_included = true;\n break;\n }\n }\n const sort_col = sort_col_included ? viz.sort : default_sort_col;\n if (sort_col) {\n const order = viz.sort_order ? viz.sort_order : \"ASC\";\n s += \"ORDER BY\\n\" + indent + sort_col + \" \" + order + \"\\n\";\n }\n }\n s += \"LIMIT 500\";\n\n return s;\n }\n\n static run(table: ApiBQTable, viz: Display, cb: Function, error_cb: Function) {\n if (viz.query_columns.length === 0) {\n cb();\n return;\n }\n const cols: BQData[] = [];\n for (const s of viz.query_columns) {\n if (BQ.skip_col(s)) {\n continue;\n }\n const c = cloneDeep(s);\n cols.push(c);\n }\n\n const q = BQ.build_query(viz);\n console.log(q);\n const body: ApiBQQuery = {\n project_id: table.project_id,\n dataset_id: table.dataset_id,\n table_id: table.id,\n query: q,\n };\n Ajax.post(\"/api/v1/bq_query\", function (data: ApiBQResponse) {\n for (let i = 0; i < data.rows.length; i++) {\n const row = data.rows[i];\n for (let j = 0; j < row.length; j++) {\n const el = row[j];\n cols[j].rows.push(el);\n }\n }\n viz.data = cols;\n cb();\n }, body, function (status: number, data: ApiErrorResponse) {\n console.error(status, data.message);\n error_cb(data);\n });\n }\n\n}", "import { ApiUpdate, ApiPreSignedUrl, ApiPage } from \"./api_data\";\nimport { Ajax } from \"../../shared/ajax\";\nimport { App } from \"./app\";\nimport { Page } from \"./page\";\n\nexport interface UpdateOpts {\n update_thumbnail: boolean;\n data_changes: boolean;\n}\n\nexport class Api {\n\n static thumbnail_upload_urls: { [id: string]: string } = {};\n static thumbnail_retry = 0;\n static presigned_url_retry = 0;\n\n static update_page(page: Page, changes: ApiUpdate, update_thumbnail: boolean = false) {\n const path = \"/api/v1/pages/\" + page.id;\n Ajax.put(path, function (data: ApiPage) {\n for (const k in App.page_sets) {\n if (App.page_sets.hasOwnProperty(k)) {\n const set = App.page_sets[k];\n for (const set_page of set) {\n if (set_page.id === page.id) {\n set_page.version = data.version;\n set_page.connections = data.connections;\n set_page.attributes = data.attributes;\n break;\n }\n }\n }\n }\n\n }, changes, function (code: number, data: any) {\n console.log(\"api error: \", code, data);\n });\n if (update_thumbnail) {\n App.new_graph_data = true;\n App.thumbnail_dirty_count = 1;\n }\n }\n\n static update_display(display_id: string, changes: ApiUpdate, opts?: UpdateOpts) {\n const path = \"/api/v1/displays/\" + display_id;\n Ajax.put(path, function () {\n //\n }, changes, function (code: number, data: any) {\n console.log(\"api error: \", code, data);\n });\n\n let update_thumbnail = true;\n let data_changes = true;\n if (opts !== undefined) {\n update_thumbnail = opts.update_thumbnail;\n data_changes = opts.data_changes;\n }\n if (update_thumbnail) {\n App.thumbnail_dirty_count++;\n }\n if (data_changes && App.selected_page) {\n for (const v of App.selected_page.viz_list) {\n if (v.viz.id === display_id) {\n v.viz.data_changes = true;\n }\n }\n }\n }\n\n static get_pre_signed_url(page_id: string, cb: Function) {\n const url = \"/api/v1/pages/\" + page_id + \"/pre_signed_url\";\n Ajax.get(url, function (data: ApiPreSignedUrl) {\n cb(data);\n });\n }\n\n static upload_thumbnail(page_id: string, data: Blob) {\n App.new_graph_data = false;\n const url = Api.thumbnail_upload_urls[page_id];\n if (url === undefined) {\n if (Api.presigned_url_retry < 3) {\n Api.presigned_url_retry++;\n Api.get_pre_signed_url(page_id, function (url_data: ApiPreSignedUrl) {\n Api.thumbnail_upload_urls[page_id] = url_data.url;\n Api.upload_thumbnail(page_id, data);\n })\n }\n return;\n }\n Api.presigned_url_retry = 0;\n const request = new XMLHttpRequest();\n\n const retry = function () {\n console.log('thumbnail error');\n console.log(request.status, request);\n if (Api.thumbnail_retry < 2) {\n delete Api.thumbnail_upload_urls[page_id];\n Api.thumbnail_retry++;\n Api.upload_thumbnail(page_id, data);\n }\n }\n\n request.onload = function () {\n if (request.status >= 200 && request.status < 400) {\n Api.thumbnail_retry = 0;\n App.thumbnail_dirty_count = 0;\n } else {\n retry();\n }\n };\n request.onerror = function () {\n retry();\n };\n request.open('PUT', url, true);\n request.setRequestHeader(\"Content-Type\", \"image/png\");\n request.send(data);\n }\n}", "export class SVG {\n\n static font = \"-apple-system, BlinkMacSystemFont, 'Inter', sans-serif\";\n\n static rect(x: number, y: number, width: number, height: number, css_class?: string,): SVGRectElement {\n const rect = document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");\n rect.setAttribute(\"x\", x + \"px\");\n rect.setAttribute(\"y\", y + \"px\");\n rect.setAttribute(\"width\", width + \"px\");\n rect.setAttribute(\"height\", height + \"px\");\n if (css_class !== undefined) {\n rect.classList.add(css_class);\n }\n return rect;\n }\n\n static svg_with_view_box(w: number, h: number): SVGSVGElement {\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"viewBox\", \"0 0 \" + w + \" \" + h);\n return svg\n }\n\n static svg(w: number, h: number, cssClass?: string): SVGSVGElement {\n const svg = SVG.svg_with_view_box(w, h);\n svg.setAttribute(\"width\", w.toString());\n svg.setAttribute(\"height\", h.toString());\n if (cssClass !== undefined) {\n svg.classList.add(cssClass);\n }\n return svg;\n }\n\n static path(d: string, cssClass?: string): SVGPathElement {\n const p = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p.setAttribute(\"d\", d);\n if (cssClass !== undefined) {\n p.classList.add(cssClass);\n }\n return p;\n }\n\n static dots(): SVGSVGElement {\n const svg = SVG.svg(20, 20, \"dots\");\n const c1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n c1.setAttribute(\"cx\", \"5\");\n c1.setAttribute(\"cy\", \"10\");\n c1.setAttribute(\"r\", \"1.5\");\n const c2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n c2.setAttribute(\"cx\", \"10\");\n c2.setAttribute(\"cy\", \"10\");\n c2.setAttribute(\"r\", \"1.5\");\n const c3 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n c3.setAttribute(\"cx\", \"15\");\n c3.setAttribute(\"cy\", \"10\");\n c3.setAttribute(\"r\", \"1.5\");\n svg.appendChild(c1);\n svg.appendChild(c2);\n svg.appendChild(c3);\n return svg;\n }\n\n static bars(): SVGSVGElement {\n const svg = SVG.svg(20, 20, \"bars\");\n const l1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l1.setAttribute(\"x1\", \"3\");\n l1.setAttribute(\"y1\", \"8\");\n l1.setAttribute(\"x2\", \"17\");\n l1.setAttribute(\"y2\", \"8\");\n l1.setAttribute(\"stroke-width\", \"2\");\n l1.setAttribute(\"stroke-linecap\", \"round\");\n const l2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l2.setAttribute(\"x1\", \"3\");\n l2.setAttribute(\"y1\", \"12\");\n l2.setAttribute(\"x2\", \"17\");\n l2.setAttribute(\"y2\", \"12\");\n l2.setAttribute(\"stroke-width\", \"2\");\n l2.setAttribute(\"stroke-linecap\", \"round\");\n svg.appendChild(l1);\n svg.appendChild(l2);\n return svg;\n }\n\n static x(w: number = 30, h: number = 30, size: number = 10): SVGSVGElement {\n const svg = SVG.svg(w, h, \"x\");\n const x_offset = (w - size) / 2;\n const y_offset = (h - size) / 2;\n const p1 = \"M\" + x_offset + \" \" + y_offset + \"L\" + (x_offset + size) + \" \" + (y_offset + size);\n const p2 = \"M\" + (x_offset + size) + \" \" + y_offset + \"L\" + x_offset + \" \" + (y_offset + size);\n svg.appendChild(SVG.path(p1));\n svg.appendChild(SVG.path(p2));\n return svg;\n }\n\n static plus_icon(box: number = 26, size: number = 14): SVGSVGElement {\n const inset = (box - size) / 2;\n const svg = SVG.svg(box, box, \"add-icon\");\n const p1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n const d1 = \"M\" + inset + \" \" + (box / 2) + \"L\" + (box - inset) + \" \" + (box / 2);\n p1.setAttribute(\"d\", d1);\n svg.appendChild(p1);\n const p2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n const d2 = \"M\" + (box / 2) + \" \" + inset + \"L\" + (box / 2) + \" \" + (box - inset);\n p2.setAttribute(\"d\", d2);\n svg.appendChild(p2);\n return svg;\n }\n\n static minus_icon(box: number = 26, size: number = 14): SVGSVGElement {\n const inset = (box - size) / 2;\n const svg = SVG.svg(box, box, \"minus-icon\");\n const d = \"M\" + inset + \" \" + (box / 2) + \"L\" + (box - inset) + \" \" + (box / 2);\n const p = SVG.path(d);\n svg.appendChild(p);\n return svg;\n }\n\n static chevron(color: string = \"#bfbfbf\"): SVGSVGElement {\n const svg = SVG.svg(10, 10, \"chevron\");\n svg.setAttribute(\"fill\", \"none\");\n svg.setAttribute(\"stroke\", color);\n svg.appendChild(SVG.path(\"M1 3L5 7L9 3\"));\n return svg;\n }\n\n static pencil(): SVGSVGElement {\n const svg = SVG.svg(16, 16, \"pencil\");\n const p1 = SVG.path(\"M2 12L1 15L4 14L15 3L13 1L2 12Z\");\n p1.setAttribute(\"stroke-linejoin\", \"round\");\n svg.appendChild(p1);\n const p2 = SVG.path(\"M13 5L11 3\");\n svg.appendChild(p2);\n return svg;\n }\n\n static logo(cssClass?: string): SVGSVGElement {\n const svg = SVG.svg(72, 62.4, \"logo\");\n if (cssClass !== undefined) {\n svg.classList.add(cssClass);\n }\n const p = SVG.path(\"M34.9046 30.5084H38.3816L36.6536 26.1546L34.9046 30.5084ZM18.5884 24.9927H16.8385V32.7821H18.5884C21.1573 32.7821 22.8626 31.3807 22.8626 28.909V28.8658C22.8617 26.4148 21.1555 24.9927 18.5884 24.9927ZM62.7736 0H9.2264C6.78168 0.00684239 4.43907 0.969404 2.71031 2.6774C0.981548 4.38541 0.00715675 6.70002 0 9.1156V53.2835C0.00715565 55.6992 0.981517 58.0139 2.71025 59.7221C4.43899 61.4302 6.7816 62.3929 9.2264 62.4H62.7736C65.2184 62.3929 67.561 61.4302 69.2898 59.7221C71.0185 58.0139 71.9928 55.6992 72 53.2835V9.1156C71.9928 6.70002 71.0185 4.38541 69.2897 2.6774C67.5609 0.969404 65.2183 0.00684239 62.7736 0ZM59.9904 21.2294L54.0993 30.747V36.5454H49.7814V30.8127L43.8921 21.2294H48.7848L51.9732 26.8082L55.1843 21.2294H59.9904ZM21.2448 6.61884H50.7552C52.6591 6.61884 54.2148 7.85684 54.2148 9.3715C54.2148 10.8862 52.6591 12.1233 50.7552 12.1233H21.2448C19.3409 12.1233 17.7852 10.8844 17.7852 9.3715C17.7852 7.85857 19.3409 6.61884 21.2448 6.61884ZM23.4689 43.9086H18.8185V55.5045H14.5225V43.9086H9.87299V40.1911H23.4698L23.4689 43.9086ZM18.4318 36.5437H12.5425V21.2294H18.521C24.0569 21.2294 27.2706 24.3797 27.2706 28.8001V28.8442C27.268 33.2628 24.0131 36.5445 18.4327 36.5445L18.4318 36.5437ZM40.4736 48.6782C40.4736 53.6224 37.6178 55.7898 33.2115 55.7898C28.8053 55.7898 26.0369 53.5792 26.0369 48.7871V40.1911H30.4003V48.7015C30.4003 50.9113 31.5299 51.9617 33.257 51.9617C34.9842 51.9617 36.1137 50.9554 36.1137 48.8113V40.1911H40.4763V48.6799L40.4736 48.6782ZM39.6214 33.8083H33.6429L32.5352 36.5445H28.0178L34.6167 21.1196H38.7579L45.3568 36.5445H40.751L39.6214 33.8083ZM60.3789 55.508H56.1056V46.7105L52.142 52.7052H52.0545L48.1172 46.7537V55.5054H43.9043V40.1911H48.4436L52.142 46.1201L55.8405 40.1911H60.3797V55.5062L60.3789 55.508Z\");\n p.setAttribute(\"fill-rule\", \"evenodd\");\n p.setAttribute(\"clip-rule\", \"evenodd\");\n p.setAttribute(\"fill\", \"#C7C8CA\");\n svg.appendChild(p);\n return svg;\n }\n\n static to_url(svg: SVGSVGElement): string {\n const s = new XMLSerializer().serializeToString(svg);\n return \"data:image/svg+xml;base64,\" + window.btoa(s);\n }\n\n static render_to_image(svg: SVGSVGElement, viz_id: string, cb: Function) {\n\n const rect = svg.getBoundingClientRect();\n const canvas = document.createElement(\"canvas\");\n const width = 480;\n const height = width / (rect.width / rect.height);\n canvas.setAttribute(\"width\", width.toString());\n canvas.setAttribute(\"height\", height.toString());\n const ctx = canvas.getContext(\"2d\");\n if (!ctx) {\n return;\n }\n\n const image = new Image;\n const s = new XMLSerializer().serializeToString(svg);\n const url = 'data:image/svg+xml;charset=utf-8,' + encodeURIComponent(s);\n image.src = url;\n\n image.onload = function () {\n ctx.drawImage(image, 0, 0);\n\n // to download:\n /*\n const data = canvas.toDataURL(\"image/png\");\n var a = document.createElement(\"a\");\n a.download = \"filename.png\";\n a.href = data;\n a.click();\n */\n\n canvas.toBlob(function (blob) {\n cb(viz_id, blob);\n }, \"image/png\");\n\n if (canvas.parentElement) {\n canvas.parentElement.removeChild(canvas);\n }\n };\n }\n\n}", "import { Rect } from \"./size\";\nimport { SVG } from \"./svg\";\n\nexport interface GraphValue {\n amount: number;\n label: string;\n}\n\nexport interface GraphTotals {\n max: number;\n totals: number[];\n}\n\nexport interface GraphScale {\n min: number;\n max: number;\n pixel_length: number;\n}\n\nexport class Graph {\n\n static totals(data: GraphValue[][]): GraphTotals {\n var totals: number[] = [];\n for (let entries of data) {\n var total = 0;\n for (let entry of entries) {\n total += entry.amount;\n }\n totals.push(total);\n }\n let max = 0;\n if (totals.length > 0) {\n max = Math.max.apply(null, totals);\n }\n return {\n max: max,\n totals: totals,\n }\n }\n\n static formated_number(n: number): string {\n return n.toLocaleString(undefined, { maximumFractionDigits: 2 });\n }\n\n static compact_number(n: number, min: number = 1e3): string {\n if (n < min) {\n return Graph.formated_number(n);\n }\n if (n < 1e6) {\n return (n / 1e3).toLocaleString(undefined, { maximumFractionDigits: 1 }) + \"K\";\n }\n if (n < 1e9) {\n return (n / 1e6).toLocaleString(undefined, { maximumFractionDigits: 1 }) + \"M\";\n }\n return (n / 1e9).toLocaleString(undefined, { maximumFractionDigits: 1 }) + \"B\";\n }\n\n static render_title(svg: SVGElement, id: string, title: string, width: number, inset: number) {\n const line_y = inset + 21;\n const title_y = inset + 15;\n\n const title_el = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\n title_el.setAttribute(\"x\", inset.toString());\n title_el.setAttribute(\"y\", title_y.toString());\n title_el.style.fontFamily = SVG.font;\n title_el.setAttribute(\"fill\", \"#333\");\n title_el.style.fontSize = \"11px\";\n title_el.innerHTML = title.toUpperCase();\n title_el.classList.add(\"s-title\");\n title_el.id = \"t_\" + id;\n svg.appendChild(title_el);\n\n for (let i = 0; i < 2; i++) {\n const l1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l1.setAttribute(\"x1\", inset.toString());\n l1.setAttribute(\"x2\", (width - inset).toString());\n l1.setAttribute(\"y1\", (line_y + (i * 2)).toString());\n l1.setAttribute(\"y2\", (line_y + (i * 2)).toString());\n l1.setAttribute(\"stroke\", \"#808080\");\n svg.appendChild(l1);\n }\n }\n\n static number_scale(val: number): number {\n const r50 = Math.sqrt(50);\n const r10 = Math.sqrt(10);\n const r2 = Math.sqrt(2);\n const power = Math.floor(Math.log(val) / Math.log(10));\n let scale = val / Math.pow(10, power);\n if (scale >= r50) {\n scale = 10;\n } else if (scale >= r10) {\n scale = 5;\n } else if (scale >= r2) {\n scale = 2;\n } else {\n scale = 1;\n }\n return scale;\n }\n\n static render_y_scale(container: SVGElement, rect: Rect, max: number): GraphScale {\n const scale_vals: number[] = [];\n const scale_labels: string[] = [];\n\n const pad = 5;\n const count = 3;\n const min = 0;\n const div = (max - min) / count;\n const power = Math.floor(Math.log(div) / Math.log(10));\n let step = Graph.number_scale(div);\n if (power >= 0) {\n step = step * Math.pow(10, power);\n } else {\n step = 1 / (Math.pow(10, -power) / step);\n }\n\n const text_el = function (label: string): SVGTextElement {\n const t = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\n t.style.fontSize = \"10px\";\n t.style.fontFamily = SVG.font;\n t.setAttribute(\"fill\", \"#cccccc\");\n t.innerHTML = label;\n return t;\n }\n\n let y = 0;\n let w = 0;\n while (y < (max + step)) {\n scale_vals.push(y);\n const l = Graph.compact_number(y);\n scale_labels.push(l);\n const t = text_el(l);\n container.appendChild(t);\n const width = t.getComputedTextLength();\n container.removeChild(t);\n w = Math.max(w, width);\n y += step;\n }\n const adjusted_max = scale_vals[scale_vals.length - 1];\n\n let idx = 0;\n for (const v of scale_vals) {\n const y = rect.height - (v / adjusted_max) * rect.height;\n const l = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l.setAttribute(\"x1\", rect.left.toString());\n l.setAttribute(\"x2\", (rect.left + rect.width).toString());\n l.setAttribute(\"y1\", (rect.top + y).toString());\n l.setAttribute(\"y2\", (rect.top + y).toString());\n l.setAttribute(\"stroke\", \"#efefef\");\n container.appendChild(l);\n\n const t = text_el(scale_labels[idx]);\n t.setAttribute(\"x\", (rect.left + rect.width - w).toString());\n t.setAttribute(\"y\", (rect.top + y - 3).toString());\n t.innerHTML = scale_labels[idx];\n container.appendChild(t);\n idx++;\n }\n\n return {\n min: 0,\n max: adjusted_max,\n pixel_length: w + pad,\n }\n }\n}", "import { SVG } from \"./svg\";\nimport { Graph, GraphValue } from \"./graph\";\nimport { Size, Rect } from \"./size\";\n\nexport class Vertbars {\n\n static data_index = \"data-index\";\n static data_sub_index = \"data-sub-index\";\n static data_object_id = \"data-object-id\";\n\n static hoverBar(display_el: SVGElement, idx: number, sub_idx: number, amount: number, date: string, item_id: string, item_name: string) {\n const off_color = \"#e4e4e4\";\n const medium_color = \"#7fdff9\";\n const on_color = \"#00C0F3\";\n const amt_els = display_el.getElementsByClassName(\"vertbar-amount\");\n const date_els = display_el.getElementsByClassName(\"vertbar-label\");\n if (amt_els.length == 0 || date_els.length == 0) {\n return;\n }\n const amt_el = amt_els[0];\n const date_el = date_els[0];\n amt_el.innerHTML = Graph.compact_number(amount, 10000);\n const title = document.createElementNS(\"http://www.w3.org/2000/svg\", \"title\");\n title.innerHTML = Graph.formated_number(amount);\n amt_el.appendChild(title);\n const label_strs = [];\n if (date.length > 0) {\n label_strs.push(date);\n }\n if (item_name.length > 0) {\n label_strs.push(item_name);\n }\n date_el.innerHTML = label_strs.join(\": \");\n const rects = display_el.querySelectorAll(\"rect.key_color_fill\");\n if (item_id.length > 0) {\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i] as HTMLElement;\n rect.classList.remove(\"hover-off\");\n rect.classList.remove(\"hover-on\");\n rect.classList.remove(\"hover-medium\");\n const data_id = rect.getAttribute(Vertbars.data_object_id);\n const data_idx = Number(rect.getAttribute(Vertbars.data_index));\n const data_sub_idx = Number(rect.getAttribute(Vertbars.data_sub_index));\n if (data_id != item_id) {\n rect.classList.add(\"hover-off\");\n rect.style.fill = off_color;\n } else {\n if (data_idx == idx && data_sub_idx == sub_idx) {\n rect.classList.add(\"hover-on\");\n rect.style.fill = on_color;\n } else {\n rect.classList.add(\"hover-medium\");\n rect.style.fill = medium_color;\n }\n }\n }\n } else {\n for (let i = 0; i < rects.length; i++) {\n const rect = rects[i];\n rect.classList.remove(\"hover-off\");\n rect.classList.remove(\"hover-on\");\n rect.classList.remove(\"hover-medium\");\n }\n }\n }\n\n static render(svg: SVGElement, id: string, title: string, data: GraphValue[][], bucket_labels: string[], color: string, inset: number = 12): Size {\n\n const show_scale = true;\n let scale_labels_width = 0;\n const max = Graph.totals(data);\n\n const header_height = 150;\n const graph_height = 150;\n const width = 400;\n const height = header_height + graph_height + (inset * 2);\n\n svg.setAttribute(\"viewBox\", \"0 0 \" + width + \" \" + height + \"\");\n\n Graph.render_title(svg, id, title, width, inset);\n\n const number = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\n number.setAttribute(\"x\", inset.toString());\n number.setAttribute(\"y\", \"120\");\n number.style.fontWeight = \"bold\";\n number.style.fontSize = \"80px\";\n number.style.letterSpacing = \"-4px\";\n number.style.fontFamily = SVG.font;\n number.setAttribute(\"fill\", color);\n number.classList.add(\"vertbar-amount\");\n svg.appendChild(number);\n\n const label = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\n label.setAttribute(\"x\", inset.toString());\n label.setAttribute(\"y\", \"145\");\n label.style.fontSize = \"12px\";\n label.style.fontFamily = SVG.font;\n label.setAttribute(\"fill\", \"#373737\");\n label.classList.add(\"vertbar-label\");\n svg.appendChild(label);\n\n if (show_scale) {\n const r: Rect = {\n left: inset,\n top: height - graph_height - inset,\n width: width - inset - inset,\n height: graph_height,\n }\n const scale = Graph.render_y_scale(svg, r, max.max);\n scale_labels_width = scale.pixel_length;\n max.max = scale.max;\n }\n\n const graph_width = width - (inset * 2) - scale_labels_width;\n\n let bucket_width = graph_width / data.length;\n let gutter = bucket_width / 3;\n if (gutter > 6) {\n gutter = 6;\n }\n bucket_width = (graph_width - ((data.length - 1) * gutter)) / data.length;\n const step = bucket_width + gutter;\n const graph = document.createElementNS(\"http://www.w3.org/2000/svg\", \"g\");\n graph.style.transform = \"scaleY(-1) translate(\" + inset + \"px, -\" + (height - inset) + \"px)\";\n svg.appendChild(graph);\n for (let i = 0; i < data.length; i++) {\n const g = document.createElementNS(\"http://www.w3.org/2000/svg\", \"g\");\n g.setAttribute(\"transform\", \"translate(\" + (i * step) + \", 0)\");\n const bg = SVG.rect(0, 0, bucket_width, graph_height, \"vert_barchart_bg\");\n bg.setAttribute(\"fill\", \"none\");\n bg.onmouseenter = function () {\n let label = \"\";\n if (bucket_labels.length > i) {\n label = bucket_labels[i];\n }\n Vertbars.hoverBar(svg, i, 0, max.totals[i], label, \"\", \"\");\n }\n g.appendChild(bg);\n const base = SVG.rect(0, 0, bucket_width, 1, \"vert_barchart_marker\");\n base.setAttribute(\"fill\", \"#e2e2e2\");\n g.appendChild(base);\n graph.appendChild(g);\n const entries = data[i];\n var offset = 0;\n for (let j = 0; j < entries.length; j++) {\n const entry = entries[j];\n const y = (offset / max.max) * graph_height;\n const h = (entry.amount / max.max) * graph_height;\n if (!isNaN(h) && h > 0) {\n const r = SVG.rect(0, y, bucket_width, h, \"key_color_fill\");\n r.setAttribute(Vertbars.data_object_id, entry.label);\n r.setAttribute(Vertbars.data_index, i.toString());\n r.setAttribute(Vertbars.data_sub_index, j.toString());\n r.setAttribute(\"fill\", color);\n g.appendChild(r);\n r.onmouseenter = function () {\n let label = \"\";\n if (bucket_labels.length > i) {\n label = bucket_labels[i];\n }\n Vertbars.hoverBar(svg, i, j, entry.amount, label, entry.label, entry.label);\n }\n }\n if (!isNaN(y)) {\n const divider_h = 1 / window.devicePixelRatio;\n const edge = SVG.rect(0, y, bucket_width, divider_h, \"vert_barchart_divider\");\n edge.setAttribute(\"fill\", \"#fff\");\n g.appendChild(edge);\n }\n offset += entry.amount;\n }\n }\n\n // set initial state\n const last_idx = max.totals.length - 1;\n if (last_idx >= 0) {\n let label = \"\";\n if (bucket_labels.length > last_idx) {\n label = bucket_labels[last_idx];\n }\n Vertbars.hoverBar(svg, 0, 0, max.totals[last_idx], label, \"\", \"\");\n }\n\n return {\n width: width,\n height: height,\n }\n }\n\n}", "import { SVG } from \"./svg\";\nimport { Size } from \"./size\";\nimport { Graph } from \"./graph\";\n\nexport class SingleNumber {\n\n static render(svg: SVGElement, id: string, title: string, number: number | null, color: string, inset: number = 12): Size {\n const height = 150;\n const width = 400;\n\n svg.setAttribute(\"viewBox\", \"0 0 \" + width + \" \" + height + \"\");\n\n Graph.render_title(svg, id, title, width, inset);\n\n const num = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\n if (number) {\n num.innerHTML = Graph.compact_number(number);\n }\n num.setAttribute(\"x\", inset.toString());\n num.setAttribute(\"y\", \"120\");\n num.style.fontWeight = \"bold\";\n num.style.fontSize = \"80px\";\n num.style.letterSpacing = \"-4px\";\n num.style.fontFamily = SVG.font;\n num.setAttribute(\"fill\", color);\n num.classList.add(\"vertbar-amount\");\n const title_el = document.createElementNS(\"http://www.w3.org/2000/svg\", \"title\");\n if (number) {\n title_el.innerHTML = Graph.formated_number(number);\n }\n num.appendChild(title_el);\n\n svg.appendChild(num);\n\n return {\n width: width,\n height: height,\n }\n }\n\n}", "export class DisplayChart {\n\n static hover(idx: number, container: HTMLElement, color: string) {\n const paths = container.getElementsByTagName(\"path\");\n const items = container.getElementsByClassName(\"key-item\");\n for (let j = 0; j < paths.length; j++) {\n const path = paths[j];\n if (j == idx) {\n path.style.fill = color;\n } else {\n path.style.fill = \"#e2e2e2\";\n }\n }\n for (let j = 0; j < items.length; j++) {\n const item = items[j] as HTMLElement;\n const block = item.querySelector(\"div.key-color-block\") as HTMLElement;\n if (j == idx) {\n if (block) {\n block.style.backgroundColor = color;\n }\n item.classList.remove(\"hover-off\");\n item.classList.add(\"hover-on\");\n } else {\n if (block) {\n block.style.backgroundColor = \"#e2e2e2\";\n }\n item.classList.remove(\"hover-on\");\n item.classList.add(\"hover-off\");\n }\n }\n }\n\n static clearHover(container: HTMLElement) {\n const paths = container.getElementsByTagName(\"path\");\n const items = container.getElementsByClassName(\"key-item\");\n for (let j = 0; j < paths.length; j++) {\n const path = paths[j];\n const color = path.getAttribute(\"data-color\");\n if (color) {\n path.style.fill = color;\n }\n }\n for (let j = 0; j < items.length; j++) {\n const item = items[j] as HTMLElement;\n const block = item.querySelector(\"div.key-color-block\") as HTMLElement;\n item.classList.remove(\"hover-off\");\n item.classList.remove(\"hover-on\");\n if (block) {\n const c = block.getAttribute(\"data-color\");\n if (c) {\n block.style.backgroundColor = c;\n }\n }\n }\n }\n}", "import { GraphValue, Graph } from \"./graph\";\nimport { SVG } from \"./svg\";\nimport { DisplayChart } from \"./display_chart\";\nimport { Size } from \"./size\";\n\nexport interface LinegraphOpts {\n render_key: boolean;\n inset: number;\n color: string;\n color_set: string[] | null;\n curve: number;\n style: string;\n render_title: boolean;\n}\n\nexport interface GraphItem {\n label: SVGElement;\n color_block: SVGElement;\n}\n\nexport class Linegraph {\n\n static hover(idx: number, paths: SVGElement[], items: GraphItem[], color: string) {\n const off_color = \"#e4e4e4\";\n for (let j = 0; j < paths.length; j++) {\n const path = paths[j];\n path.style.fill = j === idx ? color : off_color;\n }\n for (let j = 0; j < items.length; j++) {\n const item = items[j];\n if (j === idx) {\n item.label.style.fill = \"#808080\";\n item.color_block.style.fill = color;\n } else {\n item.label.style.fill = off_color;\n item.color_block.style.fill = off_color;\n }\n }\n }\n\n static clear_hover(paths: SVGElement[], items: GraphItem[], color: string) {\n for (let j = 0; j < paths.length; j++) {\n const path = paths[j];\n path.style.fill = color;\n }\n for (let j = 0; j < items.length; j++) {\n const item = items[j];\n item.label.style.fill = \"#808080\";\n item.color_block.style.fill = color;\n }\n }\n\n static render(svg: SVGElement, id: string, title: string, data: GraphValue[][], _bucket_labels: string[], opts: LinegraphOpts, ratio: number, container?: HTMLElement): Size {\n\n const max = Graph.totals(data);\n const width = 400;\n const inset = opts.inset;\n const graph_width = width - (inset * 2);\n const temp_height = 470 / ratio;\n const graph_height = temp_height - 4;\n let title_offset = 0;\n\n svg.setAttribute(\"viewBox\", \"0 0 \" + width + \" \" + temp_height + \"\");\n svg.classList.add(\"line-graph\");\n\n if (opts.render_title) {\n Graph.render_title(svg, id, title, width, inset);\n title_offset = 40;\n }\n\n if (data.length === 0) {\n return {\n width: width,\n height: temp_height,\n };\n }\n\n const item_count = data[0].length;\n const values: number[][] = [];\n const labels: string[] = [];\n for (let i = 0; i < item_count; i++) {\n const vals = [];\n for (let j = 0; j < data.length; j++) {\n const val = data[j][i];\n if (j === 0) {\n labels.push(val.label);\n }\n vals.push(val.amount);\n }\n values.push(vals);\n }\n\n const stacked = true;\n if (stacked) {\n for (let i = item_count - 2; i >= 0; i--) {\n const prev = values[i + 1];\n for (let j = 0; j < values[i].length; j++) {\n values[i][j] += prev[j];\n }\n }\n }\n\n const buckets = data.length;\n const bucket_count = opts.style === \"step\" ? buckets : buckets - 1;\n const bucket_width = graph_width / bucket_count;\n\n const graph = document.createElementNS(\"http://www.w3.org/2000/svg\", \"g\");\n graph.style.transform = \"scaleY(-1) translate(\" + inset + \"px, -\" + (graph_height + inset + title_offset) + \"px)\";\n svg.appendChild(graph);\n\n const paths: SVGElement[] = [];\n const items: GraphItem[] = [];\n\n const curve_path = function (vals: number[], item_idx: number, item_count: number): string {\n const c = opts.curve / 100;\n const start_x = 0;\n const start_y = (vals[0] / max.max) * graph_height;\n let px = start_x;\n let py = start_y;\n let d = \"M \" + start_x + \" \" + start_y;\n for (let j = 1; j < vals.length; j++) {\n const val = vals[j];\n const x = j * bucket_width;\n const y = (val / max.max) * graph_height;\n const cx1 = px + ((bucket_width / 2) * c);\n const cx2 = x - ((bucket_width / 2) * c);\n const cy1 = py;\n const cy2 = y;\n d += \" C \" + cx1 + \" \" + cy1 + \" \" + cx2 + \" \" + cy2 + \" \" + x + \" \" + y;\n px = x;\n py = y;\n }\n if (item_idx < item_count - 1) {\n const next = values[item_idx + 1];\n const n_start_x = 0;\n const n_start_y = (vals[0] / max.max) * graph_height;\n px = n_start_x;\n py = n_start_y;\n for (let j = next.length - 1; j >= 0; j--) {\n const val = next[j];\n const x = j * bucket_width;\n const y = (val / max.max) * graph_height;\n if (j === next.length - 1) {\n d += \" L \" + x + \" \" + y;\n } else {\n const cx1 = px - ((bucket_width / 2) * c);\n const cx2 = x + ((bucket_width / 2) * c);\n const cy1 = py;\n const cy2 = y;\n d += \" C \" + cx1 + \" \" + cy1 + \" \" + cx2 + \" \" + cy2 + \" \" + x + \" \" + y;\n }\n px = x;\n py = y;\n }\n } else { // last item\n d += \" L \" + graph_width + \" \" + 0;\n d += \" L \" + 0 + \" \" + 0;\n }\n return d;\n }\n\n const line_path = function (vals: number[], item_idx: number, item_count: number): string {\n const points = [];\n for (let j = 0; j < vals.length; j++) {\n const val = vals[j];\n const x = j * bucket_width;\n const y = (val / max.max) * graph_height;\n points.push(x + \" \" + y);\n }\n if (item_idx < item_count - 1) {\n const next = values[item_idx + 1];\n for (let j = next.length - 1; j >= 0; j--) {\n const val = next[j];\n const x = j * bucket_width;\n const y = (val / max.max) * graph_height;\n points.push(x + \" \" + y);\n }\n } else { // last item\n points.push(graph_width + \" \" + 0);\n points.push(0 + \" \" + 0);\n }\n const d = \"M\" + points.join(\"L\");\n return d;\n }\n\n const add_step_curve = function (idx: number, vals: number[], curve_percent: number, reverse: boolean): string {\n const val = vals[idx];\n let x = idx * bucket_width;\n if (reverse) {\n x = (idx + 1) * bucket_width; // different\n }\n const y = (val / max.max) * graph_height;\n\n let prev = val;\n if (!reverse && idx > 0) {\n prev = vals[idx - 1];\n }\n if (reverse && idx < vals.length - 1) {\n prev = vals[idx + 1];\n }\n\n let next = val;\n if (!reverse && idx < vals.length - 1) {\n next = vals[idx + 1];\n }\n if (reverse && idx > 0) {\n next = vals[idx - 1];\n }\n\n let next_x = (idx + 1) * bucket_width;\n if (reverse) {\n next_x = x - bucket_width; // different\n }\n const prev_y = (prev / max.max) * graph_height;\n const next_y = (next / max.max) * graph_height;\n const dx = Math.abs(x - next_x) / 2;\n const dy1 = Math.abs(y - prev_y) / 2;\n const dy2 = Math.abs(y - next_y) / 2;\n const d1 = (Math.min(dx, dy1) * curve_percent);\n const d2 = (Math.min(dx, dy2) * curve_percent);\n\n let path = \" \";\n\n const first = (!reverse && idx === 0) || (reverse && idx === vals.length - 1);\n if (first) {\n if (!reverse) {\n path += \"M\" + x + \" \" + y;\n }\n } else {\n // draw trailing\n const y_dir1 = prev_y > y ? -1 : 1;\n const cs_x = x;\n const cs_y = y - (d1 * y_dir1);\n let ce_x = x + d1;\n if (reverse) {\n ce_x = x - d1; // different\n }\n const ce_y = y;\n\n path += \"L\" + cs_x + \" \" + cs_y;\n const cx1 = cs_x;\n const cx2 = ce_x;\n const cy1 = cs_y + (d1 * y_dir1);\n const cy2 = ce_y;\n path += \" C \" + cx1 + \" \" + cy1 + \" \" + cx2 + \" \" + cy2 + \" \" + ce_x + \" \" + ce_y;\n }\n\n const last = (!reverse && idx === vals.length - 1) || (reverse && idx === 0);\n if (!last) {\n const y_dir2 = next_y > y ? -1 : 1;\n let cs_x = x + bucket_width - d2;\n if (reverse) {\n cs_x = x - bucket_width + d2; // different\n }\n const cs_y = y;\n let ce_x = x + bucket_width;\n if (reverse) {\n ce_x = x - bucket_width; // different\n }\n const ce_y = y - (d2 * y_dir2);\n\n path += \"L\" + cs_x + \" \" + cs_y;\n const cx1 = cs_x;\n const cx2 = ce_x;\n const cy1 = cs_y;\n const cy2 = ce_y + (d2 * y_dir2);\n path += \" C \" + cx1 + \" \" + cy1 + \" \" + cx2 + \" \" + cy2 + \" \" + ce_x + \" \" + ce_y;\n } else {\n // add line to end\n const end_x = reverse ? x - bucket_width : x + bucket_width;\n path += \"L\" + end_x + \" \" + y;\n }\n return path;\n }\n\n const step_curve_path = function (vals: number[], item_idx: number, item_count: number, curve_percent: number): string {\n let path = \"\";\n for (let j = 0; j < vals.length; j++) {\n path += add_step_curve(j, vals, curve_percent, false);\n }\n\n // bottom edge\n if (item_idx < item_count - 1) {\n const next_item = values[item_idx + 1];\n for (let j = next_item.length - 1; j >= 0; j--) {\n const val = next_item[j];\n const x = (j + 1) * bucket_width;\n const y = (val / max.max) * graph_height;\n\n // draw right edge\n if (j === next_item.length - 1) {\n path += \"L\" + x + \" \" + y;\n }\n path += add_step_curve(j, next_item, curve_percent, true);\n }\n } else { // last item\n path += \"L\" + graph_width + \" \" + 0;\n path += \"L\" + 0 + \" \" + 0;\n }\n return path;\n }\n\n const step_path = function (vals: number[], item_idx: number, item_count: number): string {\n const points = [];\n for (let j = 0; j < vals.length; j++) {\n const val = vals[j];\n const x = j * bucket_width;\n const y = (val / max.max) * graph_height;\n points.push(x + \" \" + y);\n points.push((x + bucket_width) + \" \" + y);\n }\n if (item_idx < item_count - 1) {\n const next = values[item_idx + 1];\n for (let j = next.length - 1; j >= 0; j--) {\n const val = next[j];\n const x = (j + 1) * bucket_width;\n const y = (val / max.max) * graph_height;\n points.push(x + \" \" + y);\n points.push((x - bucket_width) + \" \" + y);\n }\n } else { // last item\n points.push(graph_width + \" \" + 0);\n points.push(0 + \" \" + 0);\n }\n const d = \"M\" + points.join(\"L\");\n return d;\n }\n\n const c = opts.curve / 100;\n for (let i = 0; i < item_count; i++) {\n let shape_color = opts.color_set ? opts.color_set[i] : opts.color;\n shape_color = \"#\" + shape_color;\n const p = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p.setAttribute(\"fill\", shape_color);\n paths.push(p);\n graph.appendChild(p);\n const vals = values[i];\n if (opts.style === \"step\") {\n if (opts.curve > 5) {\n const path = step_curve_path(vals, i, item_count, c);\n p.setAttribute(\"d\", path);\n } else {\n const path = step_path(vals, i, item_count);\n p.setAttribute(\"d\", path);\n }\n } else {\n if (opts.curve > 0) {\n const path = curve_path(vals, i, item_count);\n p.setAttribute(\"d\", path);\n } else {\n const path = line_path(vals, i, item_count);\n p.setAttribute(\"d\", path);\n }\n }\n p.style.fill = shape_color;\n p.style.stroke = \"white\";\n p.style.strokeWidth = \"0.5\";\n if (container !== undefined) {\n p.setAttribute(\"data-color\", shape_color);\n p.onmouseover = function () {\n const c = \"#\" + opts.color;\n DisplayChart.hover(i, container, c);\n }\n p.onmouseout = function () {\n DisplayChart.clearHover(container);\n }\n } else {\n p.onmouseover = function () {\n Linegraph.hover(i, paths, items, shape_color);\n }\n p.onmouseout = function () {\n Linegraph.clear_hover(paths, items, shape_color);\n }\n }\n }\n\n if (!opts.render_key) {\n return {\n width: width,\n height: temp_height,\n };\n }\n\n const label_g = document.createElementNS(\"http://www.w3.org/2000/svg\", \"g\");\n label_g.style.transform = \"translate(\" + inset + \"px, \" + (graph_height + title_offset + (inset * 2)) + \"px)\";\n svg.appendChild(label_g);\n\n const line_height = 20;\n const switch_point = Math.ceil(labels.length / 2);\n const col_width = (graph_width - inset) / 2;\n const right_col_edge = col_width + inset;\n let left_offset = 0;\n let right_offset = 0;\n const text_width = col_width - 20;\n\n for (let i = 0; i < labels.length; i++) {\n const x = i < switch_point ? 0 : right_col_edge;\n const y = i < switch_point ? left_offset : right_offset;\n const g = document.createElementNS(\"http://www.w3.org/2000/svg\", \"g\");\n g.style.transform = \"translate(\" + x + \"px, \" + y + \"px)\";\n label_g.appendChild(g);\n const name = labels[i];\n const bg = SVG.rect(0, 0, col_width, line_height);\n bg.setAttribute(\"fill\", \"white\");\n g.appendChild(bg);\n const r = SVG.rect(0, 0, 10, 10);\n let shape_color = opts.color_set ? opts.color_set[i] : opts.color;\n shape_color = \"#\" + shape_color;\n r.setAttribute(\"fill\", shape_color);\n g.appendChild(r);\n const label = document.createElementNS(\"http://www.w3.org/2000/svg\", \"text\");\n label.setAttribute(\"x\", (18).toString());\n label.setAttribute(\"y\", (9).toString());\n label.style.fontSize = \"11px\";\n label.style.fontFamily = SVG.font;\n label.style.textTransform = \"uppercase\";\n label.setAttribute(\"fill\", \"#808080\");\n g.appendChild(label);\n if (i < switch_point) {\n left_offset += line_height;\n } else {\n right_offset += line_height;\n }\n const item: GraphItem = {\n label: label,\n color_block: r,\n }\n items.push(item);\n g.onmouseover = function () {\n Linegraph.hover(i, paths, items, shape_color);\n }\n g.onmouseout = function () {\n Linegraph.clear_hover(paths, items, shape_color);\n }\n\n const words = name.split(/\\s+/);\n const line: string[] = [];\n let w: string | undefined = \"\";\n while (w = words.splice(0, 1)[0]) {\n line.push(w);\n label.innerHTML = line.join(\" \");\n if (label.getComputedTextLength() > text_width) {\n line.pop();\n label.innerHTML = line.join(\" \") + \" ...\";\n break;\n }\n }\n }\n\n const labels_height = Math.max(left_offset, right_offset) - 10;\n const height = inset + title_offset + graph_height + inset + labels_height + inset;\n svg.setAttribute(\"viewBox\", \"0 0 \" + width + \" \" + height + \"\");\n\n return {\n width: width,\n height: height,\n };\n }\n\n}", "import { ApiBQTable, ApiDisplay, ApiAttribute } from \"./api_data\";\nimport { BQData, PivotMeasure } from \"./app\";\nimport { Vertbars } from \"../../shared/vertbars\";\nimport { GraphValue } from \"../../shared/graph\";\nimport { BQ } from \"./bq\";\nimport { Editor } from \"./editor\";\nimport { cloneDeep } from 'lodash';\nimport { SingleNumber } from \"../../shared/single_number\";\nimport { Linegraph, LinegraphOpts } from \"../../shared/linegraph\";\nimport { SVG } from \"../../shared/svg\";\nimport { Size } from \"../../shared/size\";\n\nexport interface GraphData {\n data: GraphValue[][],\n bucket_labels: string[],\n}\n\nexport interface DataConnection {\n viz_id: string,\n id: string,\n data: BQData,\n position: number,\n}\n\nexport interface TableConnection {\n viz_id: string,\n id: string,\n table: ApiBQTable,\n closed: boolean,\n}\n\nexport interface FilterConnection {\n viz_id: string;\n id: string;\n column: string;\n date_mode: string;\n date_min: string | null;\n date_max: string | null;\n date_current_interval: string;\n date_recent_interval: string;\n date_recent_count: number;\n text_mode: string;\n text_query: string | null;\n}\n\nexport interface AttributeApplyResult {\n pivot_op: string | null;\n pivot_facet: string | null;\n}\n\nexport class Display {\n\n id: string;\n owner_id: string;\n title: string;\n version: number;\n created_at: string;\n\n selected_table: TableConnection | null = null;\n selected_columns: DataConnection[] = [];\n group_by: string | null = null;\n group_by_interval: string | null = null;\n sort: string | null = null;\n sort_order: string | null = null;\n query_columns: BQData[] = [];\n data: BQData[] = [];\n filters: FilterConnection[] = [];\n\n count_target: string | null = null;\n count: BQData = {\n project_id: \"\",\n dataset_id: \"\",\n table_id: \"\",\n column_name: \"Count\",\n column_type: \"count\",\n rows: [],\n pivoted: false,\n pivot_facet: null,\n pivot: null,\n pivot_op: null,\n pivot_target: null,\n pivot_measures: [],\n\n operation: null,\n loading: false,\n hidden: false,\n closed: false,\n }\n\n type = \"bars\";\n aspect_ratio: number = 400 / 314;\n line_curve: number = 0;\n line_style: string = \"line\";\n closed: boolean = false;\n data_changes = false;\n\n constructor(id: string, owner_id: string, title: string, version: number, created_at: string) {\n this.id = id;\n this.owner_id = owner_id;\n this.title = title;\n this.version = version;\n this.created_at = created_at;\n }\n\n static render(viz: Display, g: SVGGElement, inset: number): Size {\n g.innerHTML = \"\";\n\n const shadow_size = 7;\n const bg = SVG.rect(shadow_size, shadow_size, (400 - (shadow_size * 2)), 180);\n bg.setAttribute(\"filter\", \"url(#shadow)\");\n bg.setAttribute(\"rx\", \"10\");\n bg.setAttribute(\"fill\", \"white\");\n bg.classList.add(\"graph-panel\");\n g.appendChild(bg);\n\n let size: Size = {\n width: 400,\n height: 180,\n }\n\n switch (viz.type) {\n case \"lines\":\n const data = Display.graph_data(viz.data);\n const opts: LinegraphOpts = {\n render_key: true,\n inset: inset,\n color: \"#00c0f3\",\n color_set: null,\n curve: viz.line_curve,\n style: viz.line_style,\n render_title: true,\n }\n size = Linegraph.render(g, viz.id, viz.title, data.data, data.bucket_labels, opts, (400 / 180));\n break;\n\n case \"number\":\n const num = Display.graph_number(viz.data);\n size = SingleNumber.render(g, viz.id, viz.title, num, \"#00c0f3\", inset);\n break;\n\n default:\n const vert_data = Display.graph_data(viz.data);\n size = Vertbars.render(g, viz.id, viz.title, vert_data.data, vert_data.bucket_labels, \"#00c0f3\", inset);\n break;\n }\n\n bg.setAttribute(\"width\", size.width - (shadow_size * 2) + \"px\");\n bg.setAttribute(\"height\", size.height - (shadow_size * 2) + \"px\");\n return size;\n }\n\n private static apply_conn_attr(conn: DataConnection, attr: ApiAttribute): AttributeApplyResult {\n const res: AttributeApplyResult = {\n pivot_op: null,\n pivot_facet: null,\n }\n if (attr.parent !== conn.id) {\n return res;\n }\n switch (attr.key) {\n\n case \"pivoted\":\n if (attr.number) {\n conn.data.pivoted = true;\n }\n break;\n\n case \"pivot_facet\":\n conn.data.pivot_facet = attr.text;\n res.pivot_facet = attr.text;\n break;\n\n case \"pivot_operation\":\n conn.data.pivot_op = attr.text;\n res.pivot_op = attr.text;\n break;\n\n case \"operation\":\n conn.data.operation = attr.text;\n break;\n\n case \"closed\":\n if (attr.number) {\n conn.data.closed = true;\n }\n break;\n\n case \"position\":\n if (attr.number) {\n conn.position = attr.number;\n }\n break;\n\n default:\n break;\n }\n return res;\n }\n\n static load_columns(viz: Display, api_viz: ApiDisplay) {\n if (!viz.selected_table || !viz.selected_table.table.columns) {\n return;\n }\n viz.selected_columns = [];\n for (const conn of api_viz.connections) {\n if (conn.key !== \"column\") {\n continue;\n }\n for (const col of viz.selected_table.table.columns) {\n if (col.name !== conn.child) {\n continue;\n }\n const data: BQData = {\n project_id: viz.selected_table.table.project_id,\n dataset_id: viz.selected_table.table.dataset_id,\n table_id: col.table_id,\n column_name: col.name,\n column_type: col.type,\n rows: [],\n pivoted: false,\n pivot_facet: null,\n pivot: null,\n pivot_op: null,\n pivot_target: null,\n pivot_measures: [],\n operation: null,\n loading: false,\n hidden: false,\n closed: false,\n }\n const c: DataConnection = {\n viz_id: viz.id,\n id: conn.id,\n data: data,\n position: 0,\n }\n viz.selected_columns.push(c);\n break;\n }\n }\n\n const columns: DataConnection[] = [];\n for (const conn of viz.selected_columns) {\n columns.push(conn);\n let pivot_op: string | null = null;\n let pivot_facet: string | null = null;\n for (const attr of api_viz.attributes) {\n const res = Display.apply_conn_attr(conn, attr);\n if (res.pivot_op) {\n pivot_op = res.pivot_op;\n }\n if (res.pivot_facet) {\n pivot_facet = res.pivot_facet;\n }\n }\n\n for (const c of api_viz.connections) {\n if (c.parent !== conn.id) {\n continue;\n }\n if (c.key === \"pivot_value\") {\n const p_data: BQData = {\n project_id: viz.selected_table.table.project_id,\n dataset_id: viz.selected_table.table.dataset_id,\n table_id: viz.selected_table.table.id,\n column_name: conn.data.column_name,\n column_type: conn.data.column_type,\n rows: [],\n pivoted: false,\n pivot_facet: pivot_facet,\n pivot: c.child,\n pivot_op: pivot_op,\n pivot_target: null,\n pivot_measures: [],\n operation: null,\n loading: false,\n hidden: false,\n closed: false,\n }\n const p_conn: DataConnection = {\n viz_id: viz.id,\n id: c.id,\n data: p_data,\n position: 0,\n }\n columns.push(p_conn);\n for (const attr of api_viz.attributes) {\n Display.apply_conn_attr(p_conn, attr);\n }\n }\n }\n }\n columns.sort(function (a, b) {\n return a.position - b.position;\n });\n viz.selected_columns = columns;\n for (const col of viz.selected_columns) {\n for (const conn of api_viz.connections) {\n if (conn.parent !== col.id) {\n continue;\n }\n if (conn.key === \"pivot_measure\") {\n const measure: PivotMeasure = {\n id: conn.id,\n column: conn.child,\n }\n col.data.pivot_measures.push(measure);\n }\n }\n for (const attr of api_viz.attributes) {\n if (attr.parent !== col.id) {\n continue;\n }\n if (attr.key === \"hidden\" && attr.number) {\n col.data.hidden = true;\n }\n }\n }\n }\n\n private static apply_table_attr(conn: TableConnection | null, attr: ApiAttribute) {\n if (!conn || attr.parent !== conn.id) {\n return;\n }\n switch (attr.key) {\n\n case \"closed\":\n if (attr.number) {\n conn.closed = true;\n }\n break;\n\n default:\n break;\n }\n }\n\n private static apply_attr(viz: Display, attr: ApiAttribute) {\n if (attr.parent !== viz.id) {\n return;\n }\n switch (attr.key) {\n case \"type\":\n if (attr.text) {\n viz.type = attr.text;\n }\n break;\n\n case \"aspect_ratio\":\n if (attr.number) {\n viz.aspect_ratio = attr.number;\n }\n break;\n\n case \"line_curve\":\n if (attr.number) {\n viz.line_curve = attr.number;\n }\n break;\n\n case \"line_style\":\n if (attr.text) {\n viz.line_style = attr.text;\n }\n break;\n\n case \"closed\":\n if (attr.number) {\n viz.closed = true;\n }\n break;\n\n case \"group_by\":\n viz.group_by = attr.text;\n break;\n\n case \"group_by_interval\":\n viz.group_by_interval = attr.text;\n break;\n\n case \"sort\":\n viz.sort = attr.text;\n break;\n\n case \"sort_order\":\n viz.sort_order = attr.text;\n break;\n\n case \"count_hidden\":\n if (attr.number) {\n viz.count.hidden = true;\n }\n break;\n\n case \"count\":\n viz.count_target = attr.text;\n break;\n\n default:\n break;\n }\n }\n\n static load_filters(viz: Display, api_viz: ApiDisplay) {\n viz.filters = [];\n for (const conn of api_viz.connections) {\n if (conn.key !== \"filter\") {\n continue;\n }\n const f: FilterConnection = {\n id: conn.id,\n viz_id: viz.id,\n column: \"\",\n date_mode: \"\",\n date_current_interval: \"\",\n date_recent_interval: \"\",\n date_recent_count: 0,\n date_min: null,\n date_max: null,\n text_mode: \"\",\n text_query: \"\",\n }\n\n for (const attr of api_viz.attributes) {\n if (attr.parent !== f.id) {\n continue;\n }\n switch (attr.key) {\n case \"column\":\n if (attr.text) {\n f.column = attr.text;\n }\n break;\n\n case \"date_mode\":\n if (attr.text) {\n f.date_mode = attr.text;\n }\n break;\n\n case \"date_current_interval\":\n if (attr.text) {\n f.date_current_interval = attr.text;\n }\n break;\n\n case \"date_recent_interval\":\n if (attr.text) {\n f.date_recent_interval = attr.text;\n }\n break;\n\n case \"date_recent_count\":\n if (attr.number) {\n f.date_recent_count = attr.number;\n }\n break;\n\n case \"date_min\":\n f.date_min = attr.text;\n break;\n\n case \"date_max\":\n f.date_max = attr.text;\n break;\n\n case \"text_mode\":\n if (attr.text) {\n f.text_mode = attr.text;\n }\n break;\n\n case \"text_query\":\n f.text_query = attr.text;\n break;\n\n default:\n break;\n }\n }\n if (f.column !== \"\") {\n viz.filters.push(f);\n }\n }\n }\n\n static parse(api_viz: ApiDisplay, tables: ApiBQTable[]): Display {\n const viz = new Display(api_viz.id, api_viz.owner_id, api_viz.title, api_viz.version, api_viz.created_at);\n for (const conn of api_viz.connections) {\n if (conn.parent === viz.id && conn.key === \"table\") {\n for (const t of tables) {\n if (t.id === conn.child) {\n const c: TableConnection = {\n viz_id: viz.id,\n id: conn.id,\n table: t,\n closed: false,\n }\n viz.selected_table = c;\n break;\n }\n }\n }\n }\n for (const attr of api_viz.attributes) {\n Display.apply_attr(viz, attr);\n Display.apply_table_attr(viz.selected_table, attr);\n }\n Display.load_columns(viz, api_viz);\n Display.load_filters(viz, api_viz);\n Display.build_query_columns(viz);\n return viz;\n }\n\n static graph_data(bq_data: BQData[]): GraphData {\n let row_count = 0;\n let number_object_idxs = [];\n let label_object_idx = -1;\n let idx = 0;\n for (const col of bq_data) {\n row_count = col.rows.length;\n\n if (BQ.numeric_col(col.column_type) || col.pivot || col.column_type === \"count\") {\n number_object_idxs.push(idx);\n }\n if (label_object_idx < 0 && BQ.date_col(col.column_type)) {\n label_object_idx = idx;\n }\n idx++;\n }\n\n const data: GraphValue[][] = [];\n const bucket_labels: string[] = [];\n for (let i = 0; i < row_count; i++) {\n const vals: GraphValue[] = [];\n\n let label = \"\";\n if (label_object_idx > -1) {\n const bucket = bq_data[label_object_idx].rows[i];\n bucket_labels.push(bucket);\n }\n if (number_object_idxs.length === 0) {\n const graph_val: GraphValue = {\n amount: 0,\n label: label,\n }\n vals.push(graph_val);\n } else {\n for (const idx of number_object_idxs) {\n const v = bq_data[idx].rows[i];\n let l = bq_data[idx].column_name;\n const p = bq_data[idx].pivot;\n if (p != null) {\n l = p;\n }\n const g_val: GraphValue = {\n amount: v,\n label: l,\n }\n vals.push(g_val);\n }\n }\n data.push(vals);\n }\n\n return {\n data: data,\n bucket_labels: bucket_labels,\n }\n }\n\n static graph_number(bq_data: BQData[]): number | null {\n for (const col of bq_data) {\n if ((BQ.numeric_col(col.column_type) || col.pivot || col.column_type === \"count\") && col.rows.length > 0) {\n const num = col.rows[0] as number;\n return num;\n }\n }\n return null;\n }\n\n static build_query_columns(viz: Display) {\n\n // copy pivot measures to sub columns\n for (const sel of viz.selected_columns) {\n if (!sel.data.pivoted) {\n continue;\n }\n const key = Editor.data_key(sel.data, false);\n for (const s of viz.selected_columns) {\n if (s.data.pivoted) {\n continue;\n }\n const k = Editor.column_key(s.data.dataset_id, s.data.table_id, s.data.column_name, null);\n if (k === key) {\n s.data.pivot_measures = sel.data.pivot_measures;\n }\n }\n }\n\n const cols: BQData[] = [];\n for (const sel of viz.selected_columns) {\n if (BQ.skip_col(sel.data)) {\n continue;\n }\n if (sel.data.pivot_measures.length === 0 || sel.data.pivot_op === null) {\n cols.push(sel.data);\n } else {\n for (const target of sel.data.pivot_measures) {\n const t = cloneDeep(sel);\n t.data.pivot_target = target.column;\n cols.push(t.data);\n }\n }\n }\n\n if (viz.count.hidden === false) {\n cols.push(viz.count);\n }\n viz.query_columns = cols;\n }\n}", "import { div } from \"./dom\";\n\nexport class Loading {\n static overlay(): HTMLDivElement {\n const loading = div(\"loading-overlay\");\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"viewBox\", \"0 0 40 40\");\n const c1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n c1.setAttribute(\"cx\", \"8\");\n c1.setAttribute(\"cy\", \"20\");\n c1.setAttribute(\"r\", \"4\");\n c1.classList.add(\"one\");\n const c2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n c2.setAttribute(\"cx\", \"20\");\n c2.setAttribute(\"cy\", \"20\");\n c2.setAttribute(\"r\", \"4\");\n c2.classList.add(\"two\");\n const c3 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n c3.setAttribute(\"cx\", \"32\");\n c3.setAttribute(\"cy\", \"20\");\n c3.setAttribute(\"r\", \"4\");\n c3.classList.add(\"three\");\n svg.appendChild(c1);\n svg.appendChild(c2);\n svg.appendChild(c3);\n loading.appendChild(svg);\n return loading;\n }\n\n static img = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAZESURBVHgBxZjbT1xFHMfnnLO7sBfuLSgQAhRRIcUS5CY0oVVJY5MmxpCYmPhW6+XRpA/6wl9gYkx86KMvPvCkGH1ToiB3iTQhomAosEVAlnJdlt2z2+/37MyyBVqW2+4vmczsmdkzn/Ob3/x+vxlNnFBaWlquhkKhGjTbUK6grGua9s7AwMAM+zs6Oozl5WVtY2NDKy8vD3d1dZniBKIdZ3BdXV2W3W7/MBwOfwKYHDzSZTFk/evg4OB1vreqqsq+u7urZWVlGRkZGewTgUDA7O/vD6AZTnROWyKDGhsbMyORyF1AfQQ4HTUnjFDQthq6rgv0ZYu4Dy8uLtYmJycFNKjt7OzoTqfT3tzc7MTYYF9f31YioPpRA5qamm6jGkb5gFAAirCOHyMhH2HiL+Ujq39mZkYUFhY+8b60tDR9e3s7HauRS1hxhGhHwHVi4tvyQ/SowiztGWjT5n5CuxdlHNqZ7enpebTv3XpFRYWtoKDAsbW1ZTgcDsM0Tc1msxmwXx0a1/BRW6Ojo2vHAuSSorqH8pqwFKTpamkB5mUfJvr2WS/eL7BJR25urhvvsME2dcDqhGRBd3B4eHhJHLLkhwI2NDT8gBdVSyBLE6g38fsLbIJ74hTS3t7uXllZyVSAqDV8rB4MBgP44IX9441D4D5H9aZFH7UtAnpR3xoaGvpFnFKmp6eDra2tfp/P58Sq2AzDsAAB6sjPzzcWFha2nwoIuLcB9SnsglARCTmB8j7g5sUZycTERKSysnIH8zix3A64Lp2QmMdVVlYWnp2d3VFjY7u4tra2EAM+RhMfFqZTpfeYQ30Hy3pmcEqwoUIAWwKYyVVigTZ1AF/s7OzUDwBiMOHoE8J0JZA1/OG984CLh4QWH/r9fu5mA46cG9LW3d1d8ASg1N4tNC3Niehu+gpe3yvOWbAxgh6P539qEK5KJyjM8QJDZQwQD+5ggCnBWM/B5r4RSZLe3t5VzB+iK5O2aMDJX4wBQupAriIEvfHXIskCMB/hqEnpc61l1uGU61AXoIPaCzNkISP5XiRZEK9XLSAssXRtdmRMGSStFXtLG0I5ta87ich0bJ3aIyTL6uqqmyHsBRHVHCG5xCMiRYJosklXo9yOy+XKsoE0X24QbnHmbH+LFAlscJsaZHQhC8RDWhojfR8dZhiOckGkSJBM0BEahJSgDgK6CCaLiTC0KVIkdNzxNogld9hAnHD6nQwhGCCFjGaWH1yXG8Ra4pqaGrdIkbS1tVFh1J7lrBF+Ixag1KJlh3j4nEiRLC0tZUpHrewwQMApId0MCwDLRIoEJ0CnXGI9eg7TLcA/RVR7VoFcFikSzJ0XB0e2Ddb/cveqXQzI+lTZIVgKubxMYAmKRz4dKdV9dGwqO0Rxut3uayLJgmNoCaDSqDFqkPYHNp+VzeDBd4RDn0oYbookC1K+Ku5cwvGwhqOpj88tQGS03WIvHtMOc5HlvCWSJPX19dUIcxkKjjWc9F/ss7LWxcXFIG4AXGhWcKlpn6gv4cD9+/5T1llLdXW1B9q6iibTfk0mCg9GRkYesD92JkGS0AWoDRE9LFGL6YiFn8E2LohzEsLB3t/gTYPSHB77oc0JNSZ27KQWS0pKdgHGK7WI3DROQL5UVFQ07vV6/eIMhXCQG2h6UKg1PmYK8we0t3wAkDI/Pz+FGykudTljoYTMQLkCyLGzgmSmDFfCjeiR2bOQZ/FJnIUm4sceuFkAxDggX0QzT+zdZqWjvg7ICPr/EacQ3Ghdxiq9jqbLSgb0mJUtAu63/eMPvZuB3bmwtHfRLJZajEgnznoZfT/CRw2JBAU3XGk5OTkv4/+voLiljSu3FsH7vGtraz8j1dtNCFAJXM27qK7xhQqUtYw6W5hgHPUULoEe4kJoFUdF68qitLQ0PROCZSxAKcYYxne7OlbgfyYB+Rvt+7gcGHgaw5FXwLivacZLbuJlOXFwpoo8KlWT2jDlx6jQGWvLOB+L+RjLu5lhRrJnzZ/QHTUg8/BSOu5Xxd7ViAqN5iGTxy4B1HMFKdtj0Pjw1NRU4Ki5j3WJDgPPRXWDS4aSrexSTmrGQ8SBmXKj0QOMAmwsEbATAcYLNtIlTFwGA38eP5loZmPJlJ0x+myj/z9GBbAu4QZ1TpxAHgM4p9NAAvOKiwAAAABJRU5ErkJggg==\";\n\n static img_light = \"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAACXBIWXMAABYlAAAWJQFJUiTwAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAARESURBVHgBxZjLa1VXFMa/e2Ni1fiImtraUiil9EVf2A5aKLTQQalQaEtLoeBMRAeOfKET/wJBBAcOnThw5FsnOnEgPhCfiIiv+EIliUajUXOv35ezVs7eJ+cm1yT3ngVf1r0556z9u2uvvc/eu4RxWrVa/YnuK+pn6hvqMfV3qVS6btdb6EqmCv8/iEYbG51NraVuUn3UU+oZ9YJ6RR22+0pUGzWVmk61m6ZR5Tdpc0o9NzHoLLo11HKqbKqaEPg55ks5Xs+0UoJ8Sf+UWa1gooAMtpRuFdURQFWDxt16qc0Z4DwT6FuUsivIZ6PcO6KRLNxGuqVIs+aZUH2p5g5QR6mz1E021hs86/cqCW32jNdlSxBPkI/eCNC6dBv1YwDlum3XdowWOCemIGcYcDkjdfn9vC6vBbiX7gvEWXtCbWKQbZiAMbYgZ2Fkrwww9t3s/VNyAmyg+5TyX6OHu6h/GaALEzTG0Mh/zo+dSLtc0mifz+sPw/vLGbg/6ZYgKfKK6Tz1z2TABZCaEwXyCmk9SnPJ0JELyAsL6VYY1KBBCmoZA97CJBtjCu6+teVZFE9nOFeGGRTcQgMUnAbA/42Ay0DeQTqy5VV2CyJAy94fSDMnyC0McBsNNrahEfwQ8RQ2316VwxlcZnDevV18cDuaZGyrB0k9lgPIzhBwEeK3xFY037oRTztD3VxmKhfZFx+1vfxFu9F86zHvtdhKtpki/RZp1yrNR1CA2dSj16d3sTRDXz5Gmj1170kUZ3pbeTdLszWk30Y6F8kuozjrRwooa/c5x19runAXxdkAkq51axPgdKSAqoUnKMg0cdtbxDPYIsAxV7VNNs/g0KJXtBo5PoorthwqxNi2EuaLB/lqCOiQ76A40zoxXHEP6M8VpIDShyjOpiFefg0BnkEM+CWKs3mItwJ9+nMV8ULh+wLrUKuqMIPdZQ7tc0hmcM+g0vwLmmxMygd0UwM47VG6fTWzC3E3L0YTjXBynyOTPSBdbu3JAGpv8DuaYAanHeRMxPV3aRhQO60A0lfVf2mXhQaawbUjGZghnA4B+ocBzXZSfUiX/DqeWN8oyADuV8Rdq6OQi37fMKBlcSfirtawX8lg8zCJFsD9hngTL13w7EWABnkQyXmLrw3l36NWTxakwaneFiOtO1/mXybDtYipRpB1dJ8g3sBLexhgHyYGp3rTNqM1E/seYx/KPlMLUEswnQe+jzSbPngeUPsZ7DjqB9P89hn1NZIDpBBMMbW9PcyYL+oCDAL/h2TSDoP5Z9Wsjt30Ltfmu4cNPLfnNMBUWwvsR+r93pr5sR7nHJ87VothVEBr7Ack9dKBeNVTyfk+mHM9e69LP+aEvckwbkCD1ADRxP0dRmYyD2BwDLjTBjcwVtt1AQagc5FMDeqyOYiPSmrB+D2a304Jrh6wcQFmYD8y0HeR1JuAvc76TfeoG0hOT8d1fPcaFnzykG9HKrUAAAAASUVORK5CYII=\";\n}", "import { div, inputSubmit, form, inputButton } from \"./dom\";\nimport { Loading } from \"./loading\";\n\nexport enum OverlayStyle {\n Classic,\n Viz,\n}\n\nexport class Overlay {\n static overlays: Overlay[] = [];\n\n panel: HTMLElement;\n cover: HTMLElement;\n cancel_cb?: Function;\n dismissible: boolean = true;\n\n constructor(style: OverlayStyle, title: string, elements: HTMLElement[], button_label: string, submit_cb: Function, cancel_cb?: Function, open_cb?: Function, delete_cb?: Function) {\n this.panel = div(\"page-overlay\", \"overlay-panel\");\n if (style === OverlayStyle.Viz) {\n this.panel.classList.add(\"viz\");\n }\n this.cover = div(\"overlay-cover\", \"page-overlay-cover\");\n this.cancel_cb = cancel_cb;\n let body: HTMLElement = div();\n if (style === OverlayStyle.Classic) {\n body = form();\n }\n\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"viewBox\", \"0 0 20 20\");\n const p1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p1.setAttribute(\"d\", \"M2 2L18 18\");\n svg.appendChild(p1);\n const p2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p2.setAttribute(\"d\", \"M18 2L2 18\");\n svg.appendChild(p2);\n svg.onclick = function (e) {\n self.close();\n e.stopPropagation();\n };\n\n const header = div(\"overlay-header\");\n if (style === OverlayStyle.Classic) {\n header.classList.add(\"key_color\");\n }\n header.innerHTML = title;\n header.appendChild(svg);\n body.appendChild(header);\n\n for (let elem of elements) {\n body.appendChild(elem);\n }\n\n const footer = div(\"overlay-footer\");\n if (delete_cb) {\n const delete_submit = inputButton(\"white_button\", \"delete\");\n delete_submit.value = \"Delete\";\n delete_submit.onclick = function (e) {\n e.preventDefault();\n delete_cb();\n }\n footer.appendChild(delete_submit);\n }\n const self = this;\n const submit = inputSubmit(\"white_button\", \"key_button\", \"key_color_background\");\n submit.value = button_label;\n footer.appendChild(submit);\n if (delete_cb === undefined) {\n submit.classList.add(\"full-width\");\n }\n\n if (style === OverlayStyle.Classic) {\n body.onsubmit = function (e) {\n e.preventDefault();\n submit_cb();\n }\n body.appendChild(footer);\n }\n this.panel.appendChild(body);\n this.cover.appendChild(this.panel);\n document.body.appendChild(this.cover);\n if (open_cb) {\n open_cb();\n }\n Overlay.overlays.push(this);\n window.setTimeout(function () {\n self.cover.classList.add(\"open\");\n }, 20);\n }\n\n close() {\n if (!this.dismissible) {\n return;\n }\n Overlay.overlays.pop();\n this.cover.classList.remove(\"open\");\n const self = this;\n window.setTimeout(function () {\n if (self.cover.parentNode) {\n self.cover.parentNode.removeChild(self.cover);\n }\n if (self.cancel_cb) {\n self.cancel_cb();\n }\n }, 120);\n }\n\n static current(): Overlay | undefined {\n if (Overlay.overlays.length == 0) {\n return undefined;\n }\n return Overlay.overlays[Overlay.overlays.length - 1];\n }\n\n static disableDismissal() {\n const current = Overlay.current();\n if (current === undefined) {\n return;\n }\n current.panel.classList.add(\"no-dismiss\");\n current.dismissible = false;\n }\n\n static enableDismissal() {\n const current = Overlay.current();\n if (current === undefined) {\n return;\n }\n current.panel.classList.remove(\"no-dismiss\");\n current.dismissible = true;\n }\n\n static close() {\n const current = Overlay.current();\n if (current === undefined) {\n return;\n }\n current.close();\n }\n\n static deleteConfirmByTypingOverlay(title: string, message: string, confirm_message: string, confirm_string: string, cb: Function): Overlay {\n const d = div(\"overlay-panel-body\");\n d.style.maxWidth = (window.innerWidth - 200) + \"px\";\n\n const settings = div(\"message\");\n const message_el = document.createElement(\"p\");\n message_el.innerHTML = message;\n const confirm_message_el = document.createElement(\"p\");\n confirm_message_el.innerHTML = confirm_message;\n const name_input = document.createElement(\"input\");\n name_input.value = \"\";\n settings.appendChild(message_el);\n settings.appendChild(confirm_message_el);\n settings.appendChild(name_input);\n d.appendChild(settings);\n\n const panel_footer = div(\"overlay-panel-footer\");\n panel_footer.appendChild(div(\"spacer\"));\n const button = document.createElement(\"a\");\n button.classList.add(\"button\", \"noselect\");\n button.innerHTML = \"Delete\";\n const disabled = \"disabled\";\n button.classList.add(disabled, \"destructive\");\n\n const loading = Loading.overlay();\n button.appendChild(loading);\n\n panel_footer.appendChild(button);\n d.appendChild(panel_footer);\n\n name_input.oninput = function () {\n if (name_input.value === confirm_string) {\n button.classList.remove(disabled);\n } else {\n button.classList.add(disabled);\n }\n };\n\n button.onclick = function (e) {\n e.preventDefault();\n if (name_input.value !== confirm_string) {\n return;\n }\n button.classList.add(\"working\");\n cb();\n };\n\n const overlay = new Overlay(OverlayStyle.Viz, title, [d], \"Delete\", function () { });\n return overlay;\n }\n\n static deleteConfirmOverlay(title: string, message: string, cb: Function): Overlay {\n const d = div(\"overlay-panel-body\");\n\n const settings = div(\"message\");\n const message_el = document.createElement(\"p\");\n message_el.innerHTML = message;\n settings.appendChild(message_el);\n d.appendChild(settings);\n\n const panel_footer = div(\"overlay-panel-footer\");\n\n const cancel = document.createElement(\"a\");\n cancel.classList.add(\"button\", \"noselect\", \"cancel\", \"half-button\");\n cancel.innerHTML = \"Cancel\";\n panel_footer.appendChild(cancel);\n cancel.onclick = function () {\n Overlay.close();\n }\n\n panel_footer.appendChild(div(\"spacer\"));\n\n const button = document.createElement(\"a\");\n button.classList.add(\"button\", \"noselect\", \"destructive\", \"half-button\");\n button.innerHTML = \"Delete\";\n\n const loading = Loading.overlay();\n button.appendChild(loading);\n\n panel_footer.appendChild(button);\n d.appendChild(panel_footer);\n\n button.onclick = function (e) {\n e.preventDefault();\n button.classList.add(\"working\");\n cb();\n };\n\n const overlay = new Overlay(OverlayStyle.Viz, title, [d], \"Delete\", function () { });\n overlay.panel.classList.add(\"small\");\n return overlay;\n }\n}\n\ndocument.addEventListener(\"keydown\", function (e) {\n if (e.keyCode === 27) { //esc\n Overlay.close();\n }\n})\n", "const months = [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"];\n\nexport function defaultDateFormat(d: Date): string {\n const month = months[d.getUTCMonth()];\n const day = d.getUTCDate();\n const year = d.getUTCFullYear();\n return month + \" \" + day + \", \" + year;\n}\n\nexport function timeAgoDateFormat(d: Date): string {\n const now = new Date();\n const span = (Number(now) - Number(d)) / 1000;\n if (span < 60) {\n return \"Just now\";\n } else if (span < 60 * 60) {\n const minutes = Math.floor(span / 60);\n const label = minutes === 1 ? \"minute\" : \"minutes\";\n return minutes + \" \" + label + \" ago\";\n } else if (span < 60 * 60 * 24) {\n const hours = Math.floor(span / (60 * 60));\n const label = hours === 1 ? \"hour\" : \"hours\";\n return hours + \" \" + label + \" ago\";\n } else {\n const opts = { year: 'numeric', month: 'short', day: 'numeric' };\n return d.toLocaleString(undefined, opts);\n }\n}\n\nexport function dateFromString(s: string): Date {\n let clean_s = s.replace(/\\+(.*)/, \"Z\");\n clean_s = clean_s.replace(\" \", \"T\");\n return new Date(clean_s);\n}\n\nexport function apiStringFromDate(d: Date): string {\n return d.toISOString();\n}", "import { SVG } from \"../../shared/svg\";\n\nexport class VizSVG {\n\n static plus(): SVGSVGElement {\n const svg = SVG.svg(24, 24, \"plus\");\n svg.appendChild(SVG.path(\"M7 12L17 12\"));\n svg.appendChild(SVG.path(\"M12 7L12 17\"));\n return svg;\n }\n\n static minus(): SVGSVGElement {\n const svg = SVG.svg(24, 24, \"plus\");\n svg.appendChild(SVG.path(\"M7 12L17 12\"));\n return svg;\n }\n\n static arrow(): SVGSVGElement {\n const svg = SVG.svg(10, 10, \"arrow\");\n svg.appendChild(SVG.path(\"M 2 1 L 7 4.5 L 2 8\"));\n return svg;\n }\n\n static date_icon(): SVGSVGElement {\n const svg = SVG.svg(12, 12, \"element-icon\");\n const r = document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");\n r.setAttribute(\"x\", \"0.5\");\n r.setAttribute(\"y\", \"0.5\");\n r.setAttribute(\"width\", \"11\");\n r.setAttribute(\"height\", \"11\");\n r.setAttribute(\"rx\", \"1\");\n svg.appendChild(SVG.path(\"M5.80859 9H6.5459V5.47705H5.81104L4.90039 6.10938V6.77344L5.76465 6.17285H5.80859V9Z\", \"icon-fill\"));\n svg.appendChild(SVG.path(\"M0.5 3L11.5 3\"));\n svg.appendChild(r);\n return svg;\n }\n\n static number_icon(): SVGSVGElement {\n const svg = SVG.svg(12, 12, \"element-icon\");\n svg.appendChild(SVG.path(\"M5.84863 11.3687H7.1084L7.69434 8.47559H9.56201L9.79639 7.23779H7.93604L8.43408 4.81348H10.2432L10.4775 3.58301H8.69043L9.25439 0.799805H8.00195L7.43066 3.58301H5.21875L5.77539 0.799805H4.53027L3.95166 3.58301H2.18652L1.9375 4.81348H3.70264L3.21924 7.23779H1.5127L1.271 8.47559H2.96289L2.38428 11.3687H3.62939L4.21533 8.47559H6.43457L5.84863 11.3687ZM4.41309 7.29639L4.92578 4.76221H7.23291L6.71289 7.29639H4.41309Z\", \"icon-fill\"));\n return svg;\n }\n\n static text_icon(): SVGSVGElement {\n const svg = SVG.svg(12, 12, \"element-icon\");\n svg.appendChild(SVG.path(\"M5.44434 10H6.60645L4.0625 2.9541H2.88574L0.341797 10H1.46484L2.11426 8.0957H4.7998L5.44434 10ZM3.41797 4.19922H3.50098L4.52148 7.2168H2.39258L3.41797 4.19922ZM9.12598 10.0879C9.82422 10.0879 10.4053 9.78516 10.7227 9.24805H10.8057V10H11.8164V6.37207C11.8164 5.25879 11.0645 4.59473 9.73145 4.59473C8.52539 4.59473 7.66602 5.17578 7.55859 6.06934H8.57422C8.69141 5.68359 9.09668 5.46387 9.68262 5.46387C10.4004 5.46387 10.7715 5.79102 10.7715 6.37207V6.83594L9.33105 6.92383C8.06641 7.00195 7.35352 7.55371 7.35352 8.50586C7.35352 9.47266 8.10059 10.0879 9.12598 10.0879ZM9.39453 9.24316C8.82324 9.24316 8.4082 8.95508 8.4082 8.46191C8.4082 7.97852 8.74023 7.71973 9.47266 7.6709L10.7715 7.58301V8.04199C10.7715 8.72559 10.1855 9.24316 9.39453 9.24316Z\", \"icon-fill\"));\n return svg;\n }\n\n static display_icon(): SVGSVGElement {\n const svg = SVG.svg(12, 12, \"element-icon\");\n const r = document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");\n r.setAttribute(\"x\", \"0.5\");\n r.setAttribute(\"y\", \"0.5\");\n r.setAttribute(\"width\", \"11\");\n r.setAttribute(\"height\", \"11\");\n r.setAttribute(\"rx\", \"1.5\");\n svg.appendChild(r);\n svg.appendChild(SVG.path(\"M4 3L8 3\"));\n return svg;\n }\n\n static display_icon_large(): SVGSVGElement {\n const svg = SVG.svg(28, 28, \"header-icon\");\n const r = SVG.rect(4.25, 5.25, 19, 17);\n r.setAttribute(\"rx\", \"2.5\");\n r.setAttribute(\"stroke-width\", \"1.5\");\n svg.appendChild(r);\n const l = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l.setAttribute(\"x1\", \"10.5\");\n l.setAttribute(\"y1\", \"9.25\");\n l.setAttribute(\"x2\", \"17.25\");\n l.setAttribute(\"y2\", \"9.25\");\n l.setAttribute(\"stroke-width\", \"1.5\");\n l.setAttribute(\"stroke-linecap\", \"round\");\n svg.appendChild(l);\n return svg;\n }\n\n static bottom_panel_icon(): SVGSVGElement {\n const svg = SVG.svg(24, 24, \"panel-icon\");\n const r = SVG.rect(4.25, 4.25, 15, 15);\n r.setAttribute(\"rx\", \"1.5\");\n r.setAttribute(\"stroke-width\", \"1.5\");\n svg.appendChild(r);\n const l = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l.setAttribute(\"x1\", \"4\");\n l.setAttribute(\"y1\", \"14.5\");\n l.setAttribute(\"x2\", \"20\");\n l.setAttribute(\"y2\", \"14.5\");\n svg.appendChild(l);\n return svg;\n }\n\n static open_icon(): SVGSVGElement {\n const svg = SVG.svg(15, 15, \"inline-icon\");\n const p = SVG.path(\"M5 1H3C1.89543 1 1 1.89543 1 3V11C1 12.1046 1.89543 13 3 13H11C12.1046 13 13 12.1046 13 11V9H11.5V11C11.5 11.2761 11.2761 11.5 11 11.5H3C2.72386 11.5 2.5 11.2761 2.5 11V3C2.5 2.72386 2.72386 2.5 3 2.5H5V1Z\");\n svg.appendChild(p);\n const p2 = SVG.path(\"M7.5 1L12.25 1C12.6642 1 13 1.33579 13 1.75L13 6.5C13 6.91421 12.6642 7.25 12.25 7.25C11.8358 7.25 11.5 6.91421 11.5 6.5V3.56066L6.78033 8.28033C6.48744 8.57322 6.01256 8.57322 5.71967 8.28033C5.42678 7.98744 5.42678 7.51256 5.71967 7.21967L10.4393 2.5H7.5C7.08579 2.5 6.75 2.16421 6.75 1.75C6.75 1.33579 7.08579 1 7.5 1Z\");\n p2.setAttribute(\"fill-rule\", \"evenodd\");\n p2.setAttribute(\"clip-rule\", \"evenodd\");\n svg.appendChild(p2);\n return svg;\n }\n\n static table_icon(): SVGSVGElement {\n const svg = SVG.svg(12, 12, \"element-icon\");\n const r = document.createElementNS(\"http://www.w3.org/2000/svg\", \"rect\");\n r.setAttribute(\"x\", \"0.5\");\n r.setAttribute(\"y\", \"0.5\");\n r.setAttribute(\"width\", \"11\");\n r.setAttribute(\"height\", \"11\");\n r.setAttribute(\"rx\", \"1\");\n svg.appendChild(r);\n svg.appendChild(SVG.path(\"M2 2.5L10 2.5\"));\n svg.appendChild(SVG.path(\"M2 5L4 5\"));\n svg.appendChild(SVG.path(\"M5 5L10 5\"));\n svg.appendChild(SVG.path(\"M2 7L4 7\"));\n svg.appendChild(SVG.path(\"M5 7L10 7\"));\n svg.appendChild(SVG.path(\"M2 9L4 9\"));\n svg.appendChild(SVG.path(\"M5 9L10 9\"));\n return svg;\n }\n\n static plus_icon(): SVGSVGElement {\n const svg = SVG.svg(12, 12, \"element-icon\");\n const p1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p1.setAttribute(\"d\", \"M2 6L10 6\");\n svg.appendChild(p1);\n const p2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p2.setAttribute(\"d\", \"M6 2L6 10\");\n svg.appendChild(p2);\n return svg;\n }\n\n static large_table_icon(): SVGSVGElement {\n const svg = SVG.svg(29, 36, \"table-icon\");\n const r = SVG.rect(0.5, 0.5, 28, 35);\n r.classList.add(\"table-bg\");\n r.setAttribute(\"fill\", \"white\");\n svg.appendChild(r);\n const r2 = SVG.rect(4, 4, 21, 3);\n r2.setAttribute(\"fill\", \"#DADADA\");\n svg.appendChild(r2);\n\n let top = 25;\n for (let i = 0; i < 3; i++) {\n const r3 = SVG.rect(4, top, 6, 1);\n r3.setAttribute(\"fill\", \"#DADADA\");\n const r4 = SVG.rect(12, top, 13, 1);\n r4.setAttribute(\"fill\", \"#DADADA\");\n svg.appendChild(r3);\n svg.appendChild(r4);\n top += 3;\n }\n return svg;\n }\n\n static visibility_icon(): SVGSVGElement {\n const svg = SVG.svg(13, 10);\n const p1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p1.setAttribute(\"fill-rule\", \"evenodd\");\n p1.setAttribute(\"clip-rule\", \"evenodd\");\n p1.setAttribute(\"d\", \"M6.5 10C11 10 13 5 13 5C13 5 11 0 6.5 0C2 0 0 5 0 5C0 5 2 10 6.5 10ZM6.5 8.25C8.29493 8.25 9.75 6.79493 9.75 5C9.75 3.20507 8.29493 1.75 6.5 1.75C4.70507 1.75 3.25 3.20507 3.25 5C3.25 6.79493 4.70507 8.25 6.5 8.25Z\");\n svg.appendChild(p1);\n const c = document.createElementNS(\"http://www.w3.org/2000/svg\", \"circle\");\n c.setAttribute(\"cx\", \"6.5\");\n c.setAttribute(\"cy\", \"5\");\n c.setAttribute(\"r\", \"1.75\");\n svg.appendChild(c);\n return svg;\n }\n\n static graph_bars(): SVGSVGElement {\n const svg = SVG.svg(16, 16, \"graph-icon\");\n const l = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l.setAttribute(\"x1\", \"4.19995\");\n l.setAttribute(\"x2\", \"4.19995\");\n l.setAttribute(\"y1\", \"13.5\");\n l.setAttribute(\"y2\", \"9.83333\");\n svg.appendChild(l);\n const l2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l2.setAttribute(\"x1\", \"6.75952\");\n l2.setAttribute(\"x2\", \"6.75952\");\n l2.setAttribute(\"y1\", \"13.5\");\n l2.setAttribute(\"y2\", \"6.16667\");\n svg.appendChild(l2);\n const l3 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l3.setAttribute(\"x1\", \"9.31982\");\n l3.setAttribute(\"x2\", \"9.31982\");\n l3.setAttribute(\"y1\", \"13.5\");\n l3.setAttribute(\"y2\", \"7.63333\");\n svg.appendChild(l3);\n const l4 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l4.setAttribute(\"x1\", \"11.8794\");\n l4.setAttribute(\"x2\", \"11.8794\");\n l4.setAttribute(\"y1\", \"13.5\");\n l4.setAttribute(\"y2\", \"2.5\");\n svg.appendChild(l4);\n return svg;\n }\n\n static graph_lines(): SVGSVGElement {\n const svg = SVG.svg(16, 16, \"graph-icon\");\n const l = document.createElementNS(\"http://www.w3.org/2000/svg\", \"line\");\n l.setAttribute(\"x1\", \"3\");\n l.setAttribute(\"x2\", \"13\");\n l.setAttribute(\"y1\", \"12.5\");\n l.setAttribute(\"y2\", \"12.5\");\n svg.appendChild(l);\n const p = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p.setAttribute(\"d\", \"M3 10.0345L5.66963 6.73563L9.34038 9.02299L13.3448 4\");\n svg.appendChild(p);\n return svg;\n }\n\n static graph_number(): SVGSVGElement {\n const svg = SVG.svg(16, 16, \"graph-icon-fill\");\n const p1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p1.setAttribute(\"d\", \"M3.45872 4.32746H2.38983L0.575195 5.51354V6.56468L2.31525 5.42831H2.35787V11.6002H3.45872V4.32746Z\");\n svg.appendChild(p1);\n const p2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p2.setAttribute(\"d\", \"M4.82605 11.6002H9.61298V10.6591H6.33883V10.6059L7.78414 9.09308C9.11582 7.7472 9.49579 7.10445 9.49579 6.29124C9.49579 5.12291 8.54409 4.22803 7.17335 4.22803C5.81326 4.22803 4.81895 5.10871 4.81895 6.43683H5.86653C5.86298 5.65558 6.36724 5.14422 7.15204 5.14422C7.89068 5.14422 8.45176 5.59877 8.45176 6.3232C8.45176 6.96595 8.06824 7.4276 7.28699 8.25502L4.82605 10.8047V11.6002Z\");\n svg.appendChild(p2);\n const p3 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p3.setAttribute(\"d\", \"M12.8908 11.6996C14.3752 11.6996 15.4654 10.8118 15.4618 9.60445C15.4654 8.6847 14.9079 8.02419 13.942 7.87504V7.81823C14.7019 7.62291 15.1955 7.02632 15.192 6.20956C15.1955 5.14067 14.3184 4.22803 12.9192 4.22803C11.584 4.22803 10.5116 5.03414 10.476 6.21666H11.5378C11.5627 5.54905 12.1912 5.14422 12.905 5.14422C13.6472 5.14422 14.1337 5.59521 14.1302 6.26638C14.1337 6.9695 13.5691 7.43115 12.763 7.43115H12.1486V8.32604H12.763C13.7715 8.32604 14.3539 8.8374 14.3539 9.56894C14.3539 10.2756 13.7395 10.755 12.8837 10.755C12.0954 10.755 11.481 10.3502 11.4384 9.70388H10.3233C10.3695 10.89 11.4207 11.6996 12.8908 11.6996Z\");\n svg.appendChild(p3);\n return svg;\n }\n\n static graph_icon(type: string): SVGSVGElement {\n switch (type) {\n case \"lines\":\n return VizSVG.graph_lines();\n\n case \"number\":\n return VizSVG.graph_number();\n\n default:\n return VizSVG.graph_bars();\n }\n }\n\n static line_style_icon(): SVGSVGElement {\n const svg = SVG.svg(20, 20, \"graph-icon\");\n svg.appendChild(SVG.path(\"M5 14.0345L8.66963 9.73563L12.3404 12.023L16.3448 7\"));\n return svg;\n }\n\n static step_style_icon(): SVGSVGElement {\n const svg = SVG.svg(20, 20, \"graph-icon\");\n svg.appendChild(SVG.path(\"M17.5 7H14V12.5H10V9H6V14.5H2\"));\n return svg;\n }\n\n}", "import { Overlay, OverlayStyle } from \"../../shared/overlay\";\nimport { App } from \"./app\";\nimport { Api } from \"./api\";\nimport { ApiAttribute, ApiUpdate, ApiConnection } from \"./api_data\";\nimport { timeAgoDateFormat } from \"../../shared/date_format\";\nimport { div } from \"../../shared/dom\";\nimport { VizSVG } from \"./viz_svg\";\nimport { TableConnection, DataConnection, Display } from \"./display\";\nimport uuid = require(\"uuid\");\nimport { Editor } from \"./editor\";\nimport { BQ } from \"./bq\";\nimport { Page } from \"./page\";\nimport { Graph } from \"../../shared/graph\";\n\nexport class TablePicker {\n\n static render_overlay(page: Page, viz: Display, selected_table: TableConnection | null) {\n const table_picker = div(\"table-picker\");\n\n const search_input = App.input(\"search\");\n search_input.placeholder = \"Search\";\n table_picker.appendChild(search_input);\n\n const list = div(\"table-picker-list\");\n table_picker.appendChild(list);\n\n const render_list = function (search: string) {\n list.innerHTML = \"\";\n if (App.table_sets[App.selected_owner_id] === undefined) {\n return;\n }\n\n for (const table of App.table_sets[App.selected_owner_id]) {\n if (search !== \"\") {\n const match = table.id.toLowerCase().indexOf(search.toLowerCase()) === 0;\n if (!match) {\n continue;\n }\n }\n const t = div(\"data-link\");\n if (selected_table && selected_table.table.id === table.id) {\n t.classList.add(\"disabled\");\n }\n t.innerText = table.id;\n t.appendChild(VizSVG.large_table_icon());\n const count = div(\"count\");\n count.innerText = Graph.compact_number(table.row_count);\n t.appendChild(count);\n const label = div(\"meta\");\n const date = new Date(table.creation_time);\n label.innerText = timeAgoDateFormat(date);\n t.appendChild(label);\n list.appendChild(t);\n t.onclick = function () {\n if (selected_table && selected_table.table.id === table.id) {\n return;\n }\n\n const update: ApiUpdate = {\n attributes: [],\n connections: [],\n }\n // remove group by\n viz.group_by = null;\n viz.group_by_interval = null;\n\n const g_attr: ApiAttribute = {\n parent: viz.id,\n key: \"group_by\",\n text: null,\n number: null,\n }\n const int_attr: ApiAttribute = {\n parent: viz.id,\n key: \"group_by_interval\",\n text: null,\n number: null,\n }\n update.attributes.push(g_attr);\n update.attributes.push(int_attr);\n\n // remove existing conns\n if (viz.selected_table) {\n const del_conn: ApiConnection = {\n id: viz.selected_table.id,\n parent: viz.id,\n key: \"table\",\n child: viz.selected_table.table.id,\n deleted: true,\n }\n update.connections.push(del_conn);\n\n for (const s of viz.selected_columns) {\n const c: ApiConnection = {\n id: s.id,\n parent: viz.id,\n key: \"column\",\n child: s.data.column_name,\n deleted: true,\n }\n update.connections.push(c);\n }\n }\n\n const conn: TableConnection = {\n viz_id: viz.id,\n id: uuid(),\n table: table,\n closed: false,\n }\n viz.selected_table = conn;\n const api_conn: ApiConnection = {\n id: conn.id,\n parent: viz.id,\n key: \"table\",\n child: table.id,\n deleted: false,\n }\n update.connections.push(api_conn);\n\n // add column conns\n viz.selected_columns = [];\n\n // just the first number and date columns visible\n const visible_cols: string[] = [];\n let numeric_col_found = false;\n let date_col_found = false;\n let sort_col: string | null = null;\n\n if (table.columns) {\n for (const col of table.columns) {\n if (!numeric_col_found && BQ.numeric_col(col.type)) {\n numeric_col_found = true;\n visible_cols.push(col.name);\n }\n if (!date_col_found && BQ.date_col(col.type)) {\n date_col_found = true;\n visible_cols.push(col.name);\n sort_col = col.name;\n }\n }\n\n if (!sort_col && table.columns.length > 0) {\n sort_col = table.columns[0].name;\n }\n }\n\n if (numeric_col_found) {\n viz.count.hidden = true;\n const count: ApiAttribute = {\n parent: viz.id,\n key: \"count_hidden\",\n text: null,\n number: 1,\n };\n update.attributes.push(count);\n }\n\n if (sort_col) {\n viz.sort = sort_col;\n viz.sort_order = Editor.sort_orders[0].value;\n const sort: ApiAttribute = {\n parent: viz.id,\n key: \"sort\",\n text: sort_col,\n number: null,\n };\n const order: ApiAttribute = {\n parent: viz.id,\n key: \"sort_order\",\n text: Editor.sort_orders[0].value,\n number: null,\n };\n update.attributes.push(sort);\n update.attributes.push(order);\n }\n\n if (table.columns) {\n if (visible_cols.length === 0 && table.columns.length > 0) {\n visible_cols.push(table.columns[0].name);\n }\n\n for (let i = 0; i < table.columns.length; i++) {\n const col = table.columns[i];\n const data = Editor.column_selection_data(viz.id, conn, col, i);\n const c: DataConnection = {\n viz_id: viz.id,\n id: data.connection_id,\n data: data.col_data,\n position: i,\n }\n\n if (!visible_cols.includes(col.name)) {\n const attr: ApiAttribute = {\n parent: c.id,\n key: \"hidden\",\n text: null,\n number: 1,\n }\n c.data.hidden = true;\n update.attributes.push(attr);\n }\n\n viz.selected_columns.push(c);\n\n update.attributes = update.attributes.concat(data.attributes);\n update.connections = update.connections.concat(data.connections);\n\n if (App.user && col.name === visible_cols[0]) {\n const id = conn.id + \":\" + data.connection_id;\n const selection_attr: ApiAttribute = {\n parent: App.user.id,\n key: \"selected_element\",\n text: id,\n number: null,\n }\n update.attributes.push(selection_attr);\n page.selected_element = id;\n }\n }\n }\n\n Api.update_display(viz.id, update);\n viz.query_columns = [];\n App.render();\n Overlay.close();\n\n }\n }\n }\n render_list(\"\");\n\n search_input.oninput = function () {\n render_list(search_input.value);\n }\n\n const overlay = new Overlay(OverlayStyle.Viz, \"Select Table\", [table_picker], \"\", function () {\n //\n }, undefined, function () {\n search_input.focus();\n });\n overlay.panel.classList.add(\"overlay-table-picker\");\n\n }\n\n}", "import { SVG } from \"./svg\";\nimport { div, anchor, span } from \"./dom\";\n\nexport interface MenuDom {\n button: Element;\n options: HTMLElement;\n options_wrapper: HTMLElement,\n container: HTMLElement;\n}\n\nexport class Menu {\n\n static menu_open = false;\n\n static menu(close_cb?: Function): MenuDom {\n const contain = div(\"menu\", \"no-selection\", \"flex\");\n const wrap = div(\"dropdown-options-wrapper\");\n wrap.tabIndex = -1;\n wrap.style.display = \"none\";\n\n wrap.onblur = function () {\n wrap.style.display = \"none\";\n window.setTimeout(function () {\n wrap.removeAttribute(\"visible\");\n }, 150);\n if (close_cb) {\n close_cb();\n }\n Menu.menu_open = false;\n };\n wrap.onclick = function (e) {\n e.stopPropagation();\n return false;\n }\n\n const dots = SVG.dots();\n\n contain.appendChild(dots);\n\n const opts = div(\"dropdown-options\");\n wrap.appendChild(opts);\n contain.appendChild(wrap);\n\n const menu = {\n button: dots,\n container: contain,\n options: opts,\n options_wrapper: wrap,\n }\n\n dots.onmousedown = function (e) {\n e.stopPropagation();\n }\n\n dots.onclick = function (e) {\n e.stopPropagation();\n Menu.show(menu);\n }\n\n wrap.onkeydown = function (e) {\n if (e.keyCode == 27) { // esc\n wrap.blur();\n }\n }\n\n return menu;\n }\n\n static show(menu: MenuDom) {\n if (menu.options_wrapper.getAttribute(\"visible\") === \"true\") {\n return;\n }\n menu.options_wrapper.style.display = \"block\";\n menu.options_wrapper.setAttribute(\"visible\", \"true\");\n menu.options_wrapper.focus();\n Menu.menu_open = false;\n }\n\n static add_menu_header(menu: MenuDom, title: string, sub: string) {\n const d = div(\"menu-head\");\n d.innerText = title;\n const s = div(\"menu-head-sub\");\n s.innerText = sub;\n d.appendChild(s);\n menu.options.appendChild(d);\n }\n\n static add_menu_item(menu: MenuDom, label: string, cb: Function, shortcut?: string) {\n const a = anchor();\n a.innerText = label;\n if (shortcut !== undefined) {\n const s = span(\"shortcut\");\n s.innerText = shortcut;\n a.appendChild(s);\n }\n a.onmousedown = function (e) {\n e.stopPropagation();\n }\n a.onclick = function (e) {\n menu.options_wrapper.blur();\n cb();\n e.stopPropagation();\n return false;\n }\n menu.options.appendChild(a);\n }\n\n static add_menu_divider(menu: MenuDom) {\n const hr = document.createElement(\"hr\");\n menu.options.appendChild(hr);\n }\n}", "export enum InputCallbackType { Input, Change, Enter, Escape, Done, Clear }", "export class Constants {\n static period_am = \"AM\";\n static period_pm = \"PM\";\n static selected_css_class = \"selected\";\n static open_css_class = \"open\";\n static data_id_key = \"data-id\";\n static data_object_id_key = \"data-object-id\";\n static data_category_id_key = \"data-category-id\";\n static data_category_name_key = \"data-category-name\";\n static data_display_id_key = \"data-display-id\";\n static data_name_key = \"data-name\";\n static data_username_key = \"data-username\";\n static data_title_key = \"data-title\";\n static data_value_key = \"data-value\";\n static data_units_id_key = \"data-units-id\";\n static data_units_plural_key = \"data-units-plural\";\n static data_units_singular_key = \"data-units-singular\";\n static data_units_abbr_key = \"data-units-abbr\";\n static data_description_key = \"data-description\";\n static data_start_key = \"data-start\";\n static data_end_key = \"data-end\";\n static data_auto_start_key = \"data-auto-start\";\n static data_auto_end_key = \"data-auto-end\";\n static data_min_key = \"data-min\";\n static data_max_key = \"data-max\";\n static data_autocomplete_disabled = \"data-autocomplete-disabled\";\n static key_left = \"ArrowLeft\";\n static key_right = \"ArrowRight\";\n static key_up = \"ArrowUp\";\n static key_down = \"ArrowDown\";\n static key_enter = \"Enter\";\n static key_escape = \"Escape\";\n}", "export class Constants {\n static period_am = \"AM\";\n static period_pm = \"PM\";\n}", "import { Constants } from \"../classic/ts/constants\";\n\nexport class DateLocale {\n\n static twelve_hour_time: boolean | undefined;\n static day_first_date: boolean | undefined;\n\n static formatTwelveHour(): boolean {\n const test_string = new Date().toLocaleString();\n return test_string.match(/AM|PM/) != null;\n }\n\n static formatDayFirst(): boolean {\n const offset = new Date().getTimezoneOffset();\n const offset_hours = (offset / 60) + 1;\n const day = 7;\n const month = 4;\n const year = 1999;\n const test_date = new Date(Date.UTC(year, (month - 1), day, offset_hours, 0, 0));\n const opts = { year: 'numeric', month: 'numeric', day: 'numeric' };\n const str = test_date.toLocaleDateString(undefined, opts);\n const d_idx = str.indexOf(String(day));\n const m_idx = str.indexOf(String(month));\n const y_idx = str.indexOf(String(year));\n let day_first = true;\n if (d_idx !== undefined && m_idx !== undefined && y_idx !== undefined) {\n if (y_idx > m_idx && m_idx < d_idx) {\n day_first = false;\n }\n }\n return day_first;\n }\n\n static checkFormatStyle() {\n if (DateLocale.twelve_hour_time === undefined) {\n DateLocale.twelve_hour_time = DateLocale.formatTwelveHour();\n }\n if (DateLocale.day_first_date === undefined) {\n DateLocale.day_first_date = DateLocale.formatDayFirst();\n }\n }\n\n static formatTime(date: Date): string {\n DateLocale.checkFormatStyle();\n let hour = date.getHours();\n const minute = date.getMinutes();\n var am_pm = hour >= 12 ? Constants.period_pm : Constants.period_am;\n if (DateLocale.twelve_hour_time) {\n hour = hour % 12;\n if (hour == 0) {\n hour = 12;\n }\n }\n let minute_str = String(minute);\n if (minute < 10) {\n minute_str = \"0\" + minute_str;\n }\n let s = hour + \":\" + minute_str;\n if (DateLocale.twelve_hour_time) {\n s += \" \" + am_pm;\n }\n return s;\n }\n\n static formatFullDate(date: Date): string {\n DateLocale.checkFormatStyle();\n const month = date.toLocaleString(undefined, { month: \"short\" });\n const day = date.getDate();\n const year = date.getFullYear();\n let hour = date.getHours();\n const minute = date.getMinutes();\n var am_pm = hour >= 12 ? Constants.period_pm : Constants.period_am;\n if (DateLocale.twelve_hour_time) {\n hour = hour % 12;\n if (hour == 0) {\n hour = 12;\n }\n }\n let minute_str = String(minute);\n if (minute < 10) {\n minute_str = \"0\" + minute_str;\n }\n let s = \"\";\n if (DateLocale.day_first_date) {\n s = day + \" \" + month + \" \";\n } else {\n s = month + \" \" + day + \", \";\n }\n s = s + year + \" \" + hour + \":\" + minute_str;\n if (DateLocale.twelve_hour_time) {\n s += \" \" + am_pm;\n }\n return s;\n }\n\n static formatDay(date: Date): string {\n DateLocale.checkFormatStyle();\n const month = date.toLocaleString(undefined, { month: \"long\" });\n const day = date.getDate();\n const year = date.getFullYear();\n let s = \"\";\n if (DateLocale.day_first_date) {\n s = day + \" \" + month + \" \";\n } else {\n s = month + \" \" + day + \", \";\n }\n s = s + year;\n return s;\n }\n\n static formatRecentDay(date: Date): string {\n const now = new Date();\n const day_ago = new Date(now.getTime() - 86400000);\n const today = function (d: Date): boolean {\n return d.getDate() == now.getDate() &&\n d.getMonth() == now.getMonth() &&\n d.getFullYear() == now.getFullYear();\n }\n const yesterday = function (d: Date): boolean {\n return d.getDate() == day_ago.getDate() &&\n d.getMonth() == day_ago.getMonth() &&\n d.getFullYear() == day_ago.getFullYear();\n }\n if (today(date)) {\n return \"Today\";\n } else if (yesterday(date)) {\n return \"Yesterday\";\n } else {\n return date.toLocaleString(undefined, { month: \"short\", day: \"numeric\", weekday: \"short\" });\n }\n }\n}", "import { div, span } from './dom';\nimport { InputCallbackType } from './input_callback';\nimport { Constants } from './constants';\nimport { DateLocale } from './date_locale';\n\nconst month_day_counts = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst data_min_key = \"data-min\";\nconst data_max_key = \"data-max\";\nconst data_value_key = \"data-value\";\nconst partial_key = \"data-value-partial\";\n\nexport interface DateInputCallback {\n (date: Date | null, type: InputCallbackType): void;\n}\n\ninterface DateValues {\n month: number;\n day: number;\n year: number;\n hour: number;\n minute: number;\n period: string;\n}\n\nexport enum DatePickerType {\n DateTime,\n Date,\n}\n\nexport interface DateInputOptions {\n UTC: boolean;\n Force24Hour: boolean,\n ShowCalendar: boolean,\n Type: DatePickerType,\n ShowClear: boolean,\n}\n\nfunction viewDateAMPMInput(initial_value: string, cb: (t: InputCallbackType) => any, prev_cb: any, next_cb: any, disabled: boolean, focus_cb?: Function, blur_cb?: Function): HTMLDivElement {\n const d = div(\"two-digit\", \"am-pm\");\n\n function update(s: string) {\n d.setAttribute(data_value_key, s);\n d.innerHTML = s;\n }\n\n update(initial_value);\n if (!disabled) {\n d.tabIndex = 0;\n }\n\n function toggle() {\n if (d.getAttribute(data_value_key) == Constants.period_am) {\n update(Constants.period_pm);\n } else {\n update(Constants.period_am);\n }\n }\n\n d.onkeydown = function (e) {\n if (e.keyCode === 37 || e.key == Constants.key_left) { // left\n prev_cb();\n e.preventDefault();\n } else if (e.keyCode === 38 || e.key == Constants.key_up) { // up\n toggle();\n cb(InputCallbackType.Input);\n e.preventDefault();\n } else if (e.keyCode === 39 || e.key == Constants.key_right) { // right\n next_cb();\n e.preventDefault();\n } else if (e.keyCode === 40 || e.key == Constants.key_down) { // down\n toggle();\n cb(InputCallbackType.Input);\n e.preventDefault();\n } else if (e.keyCode === 65 || e.key == \"a\") { // a\n update(Constants.period_am);\n e.preventDefault();\n cb(InputCallbackType.Input);\n } else if (e.keyCode === 80 || e.key == \"p\") { // p\n update(Constants.period_pm);\n e.preventDefault();\n cb(InputCallbackType.Input);\n } else if (e.keyCode == 13 || e.key == Constants.key_enter) { // enter\n cb(InputCallbackType.Enter);\n e.preventDefault();\n } else if (e.keyCode == 27 || e.key == Constants.key_escape) { // esc\n cb(InputCallbackType.Escape);\n e.preventDefault();\n e.stopPropagation();\n }\n };\n d.onfocus = function () {\n if (focus_cb !== undefined) {\n focus_cb();\n }\n };\n d.onblur = function () {\n if (blur_cb !== undefined) {\n blur_cb();\n }\n };\n return d;\n}\n\nfunction updateNumberInput(elem: HTMLDivElement, n: number, pad_label: boolean, concat: boolean = false) {\n let max_string = elem.getAttribute(data_max_key) || \"\";\n const max = Number(max_string);\n const max_characters = max_string.length;\n let label = String(n);\n if (concat) {\n let s = elem.getAttribute(partial_key);\n if (!s) {\n s = \"\";\n }\n if (s.length >= max_characters) {\n s = s.slice(-(max_characters - 1));\n }\n if (Number(s + String(n)) <= max) {\n s = s + String(n);\n elem.setAttribute(partial_key, s);\n label = s;\n } else {\n elem.setAttribute(partial_key, String(n));\n }\n } else {\n elem.setAttribute(data_value_key, String(n));\n }\n if (pad_label && label.length === 1) {\n label = \"0\" + label;\n }\n elem.innerHTML = label;\n}\n\nexport function viewNumberInput(initial_value: number, min: number, initial_max: number, cb: (t: InputCallbackType) => any, prev_cb: Function, next_cb: Function, range_cb: Function, disabled: boolean, focus_cb?: Function, blur_cb?: Function, pad_label: boolean = false): HTMLDivElement {\n const d = div();\n if (String(initial_value).length < 3) {\n d.classList.add(\"two-digit\");\n } else {\n d.classList.add(\"four-digit\");\n }\n\n const previous_key = \"data-value-previous\";\n const timer_key = \"data-timer\";\n\n d.setAttribute(data_max_key, String(initial_max));\n\n function applyPartial(t: InputCallbackType) {\n const s = d.getAttribute(partial_key);\n if (!s) {\n return;\n }\n let n = Number(s);\n const max_string = d.getAttribute(data_max_key) || \"\";\n const max = Number(max_string);\n const val = Number(d.getAttribute(data_value_key));\n if (n < min) {\n n = val;\n } else if (n > max) {\n n = val;\n }\n d.setAttribute(partial_key, \"\");\n const ok = range_cb(n);\n if (!ok) {\n n = Number(d.getAttribute(previous_key));\n }\n updateNumberInput(d, n, pad_label);\n if (ok) {\n cb(t);\n }\n }\n\n updateNumberInput(d, initial_value, pad_label);\n if (!disabled) {\n d.tabIndex = 0;\n }\n\n const up_input = function () {\n let value = Number(d.getAttribute(data_value_key));\n const max_string = d.getAttribute(data_max_key) || \"\";\n const max = Number(max_string);\n if (value + 1 <= max) {\n value++;\n } else {\n value = min;\n }\n const ok = range_cb(value);\n if (ok) {\n updateNumberInput(d, value, pad_label);\n cb(InputCallbackType.Input);\n }\n };\n\n const down_input = function () {\n let value = Number(d.getAttribute(data_value_key));\n const max_string = d.getAttribute(data_max_key) || \"\";\n const max = Number(max_string);\n if (value - 1 >= min) {\n value--;\n } else {\n value = max;\n }\n const ok = range_cb(value);\n if (ok) {\n updateNumberInput(d, value, pad_label);\n cb(InputCallbackType.Input);\n }\n };\n\n const number_input = function (n: number) {\n const v = d.getAttribute(data_value_key);\n if (typeof (v) === \"string\") {\n d.setAttribute(previous_key, v);\n }\n const _t = d.getAttribute(timer_key);\n if (_t) {\n clearTimeout(Number(_t));\n }\n const t = setTimeout(function () {\n applyPartial(InputCallbackType.Change);\n }, 500);\n d.setAttribute(timer_key, String(t));\n updateNumberInput(d, n, pad_label, true);\n };\n\n d.onkeydown = function (e) {\n const num = Number(e.key);\n if (e.keyCode === 37 || e.key == Constants.key_left) { // left\n prev_cb();\n e.preventDefault();\n } else if (e.keyCode === 38 || e.key == Constants.key_up) { // up\n up_input();\n e.preventDefault();\n } else if (e.keyCode === 39 || e.key == Constants.key_right) { // right\n next_cb();\n e.preventDefault();\n } else if (e.keyCode === 40 || e.key == Constants.key_down) { // down\n down_input();\n e.preventDefault();\n } else if (e.keyCode == 13 || e.key == Constants.key_enter) { // enter\n const s = d.getAttribute(partial_key);\n if (s) {\n applyPartial(InputCallbackType.Enter);\n } else {\n cb(InputCallbackType.Enter);\n }\n e.preventDefault();\n } else if (e.keyCode == 27 || e.key == Constants.key_escape) { // esc\n cb(InputCallbackType.Escape);\n e.preventDefault();\n e.stopPropagation();\n } else if (e.keyCode > 47 && e.keyCode < 58 || num >= 0 && num < 10) { // numeric\n let n = e.keyCode - 48;\n if (n < 0) {\n n = num;\n }\n number_input(n);\n e.preventDefault();\n }\n };\n d.onkeyup = function (e) {\n if (e.keyCode === 38 || e.key == Constants.key_up) { // up\n cb(InputCallbackType.Change);\n e.preventDefault();\n } else if (e.keyCode === 40 || e.key == Constants.key_down) { // down\n cb(InputCallbackType.Change);\n e.preventDefault();\n }\n };\n d.onfocus = function () {\n if (focus_cb !== undefined) {\n focus_cb();\n }\n };\n d.onblur = function () {\n if (blur_cb !== undefined) {\n blur_cb();\n }\n };\n d.onclick = function (e) {\n e.stopPropagation();\n }\n d.onmousedown = function (e) {\n e.stopPropagation();\n }\n return d;\n}\n\nfunction renderCalendar(elem: HTMLDivElement, start: Date, selected: Date, opts: DateInputOptions, cb: DateInputCallback) {\n elem.innerHTML = \"\";\n const month = start.getMonth();\n const year = start.getFullYear();\n const first = new Date(year, month);\n const days = new Date(year, month + 1, 0).getDate();\n let offset = first.getDay() - 1; // monday based\n if (offset < 0) {\n offset = 6;\n }\n\n const table = document.createElement(\"table\");\n\n const prev = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n prev.classList.add(\"prev\");\n prev.setAttribute(\"viewBox\", \"0 0 20 20\");\n const p1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p1.setAttribute(\"d\", \"M1 9L19 9\");\n prev.appendChild(p1);\n const p2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n p2.setAttribute(\"d\", \"M6 4L1 9L6 14\");\n prev.appendChild(p2);\n prev.onclick = function () {\n const d = new Date(start.getFullYear(), start.getMonth() - 1);\n renderCalendar(elem, d, selected, opts, cb);\n }\n\n const next = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n next.classList.add(\"next\");\n next.setAttribute(\"viewBox\", \"0 0 20 20\");\n const n1 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n n1.setAttribute(\"d\", \"M1 9L19 9\");\n next.appendChild(n1);\n const n2 = document.createElementNS(\"http://www.w3.org/2000/svg\", \"path\");\n n2.setAttribute(\"d\", \"M14 4L19 9L14 14\");\n next.appendChild(n2);\n next.onclick = function () {\n const d = new Date(start.getFullYear(), start.getMonth() + 1);\n renderCalendar(elem, d, selected, opts, cb);\n }\n\n const title_row = document.createElement(\"tr\");\n const title = document.createElement(\"th\");\n title.classList.add(\"title\");\n title.colSpan = 7;\n title.innerText = start.toLocaleString(undefined, { month: \"long\", year: \"numeric\" });\n title.appendChild(prev);\n title.appendChild(next);\n title_row.appendChild(title);\n table.appendChild(title_row);\n\n const labels = [\"Mo\", \"Tu\", \"We\", \"Th\", \"Fr\", \"Sa\", \"Su\"];\n const header_row = document.createElement(\"tr\");\n header_row.classList.add(\"labels\")\n for (const label of labels) {\n const td = document.createElement(\"td\");\n td.innerText = label;\n header_row.appendChild(td);\n }\n table.appendChild(header_row);\n\n const today = new Date();\n let idx = offset * -1;\n while (idx <= days) {\n const tr = document.createElement(\"tr\");\n for (let i = 0; i < 7; i++) {\n const td = document.createElement(\"td\");\n if (idx >= 0 && idx < days) {\n td.classList.add(\"date-option\");\n const day = idx + 1;\n td.innerText = day.toString();\n if (selected.getDate() === day && selected.getMonth() === month && selected.getFullYear() === year) {\n td.classList.add(\"selected\", \"key_color_background\");\n }\n const d = new Date(year, month, day);\n if (today.getDate() === d.getDate() && today.getMonth() === d.getMonth() && today.getFullYear() === d.getFullYear()) {\n td.classList.add(\"today\");\n }\n td.addEventListener(\"click\", function () {\n const els = table.querySelectorAll(\"td\");\n for (let i = 0; i < els.length; i++) {\n const el = els[i];\n el.classList.remove(\"selected\", \"key_color_background\");\n }\n td.classList.add(\"selected\", \"key_color_background\");\n const d = new Date(year, month, day);\n selected = d;\n cb(d, InputCallbackType.Change);\n });\n }\n tr.appendChild(td);\n idx++;\n }\n table.appendChild(tr);\n }\n\n const tr = document.createElement(\"tr\");\n const td = document.createElement(\"td\");\n td.setAttribute(\"colspan\", \"7\");\n td.classList.add(\"button-contain\");\n tr.appendChild(td);\n table.appendChild(tr);\n const buttons = div(\"buttons\")\n td.appendChild(buttons);\n\n if (opts.ShowClear) {\n const c = span(\"button\");\n c.innerText = \"Clear\";\n buttons.appendChild(c);\n c.onclick = function () {\n cb(null, InputCallbackType.Clear);\n }\n const space = span(\"button-space\");\n buttons.appendChild(space);\n }\n\n const d = span(\"button\");\n d.innerText = \"Done\";\n buttons.appendChild(d);\n d.onclick = function () {\n cb(selected, InputCallbackType.Done);\n }\n\n elem.appendChild(table);\n}\n\nfunction viewCalendarInput(date: Date, opts: DateInputOptions, cb: DateInputCallback): HTMLDivElement {\n const cal = div(\"calendar\");\n renderCalendar(cal, date, date, opts, cb);\n return cal;\n}\n\nexport function viewDatePicker(date: Date, min: Date, max: Date, disabled: boolean, cb: DateInputCallback, options: DateInputOptions, focus_cb?: Function, blur_cb?: Function): HTMLDivElement {\n const wrapper = div(\"date-selector-wrapper\");\n\n const d = div(\"date-selector\");\n if (disabled) {\n d.classList.add(\"disabled\");\n }\n d.setAttribute(data_min_key, String(Number(min)));\n d.setAttribute(data_max_key, String(Number(max)));\n\n let twelve_hour = false;\n if (!options.Force24Hour) {\n twelve_hour = DateLocale.formatTwelveHour();\n }\n const day_first = DateLocale.formatDayFirst();\n const month = options.UTC ? date.getUTCMonth() : date.getMonth();\n const day = options.UTC ? date.getUTCDate() : date.getDate();;\n const year = options.UTC ? date.getUTCFullYear() : date.getFullYear();\n let hour = options.UTC ? date.getUTCHours() : date.getHours();\n const minute = options.UTC ? date.getUTCMinutes() : date.getMinutes();\n var am_pm = hour >= 12 ? Constants.period_pm : Constants.period_am;\n if (twelve_hour) {\n hour = hour % 12;\n if (hour == 0) {\n hour = 12;\n }\n }\n\n const date_lock = \"date-lock\";\n const date_active = \"date-active\";\n\n const on_fucus = function () {\n if (focus_cb !== undefined) {\n focus_cb();\n }\n wrapper.classList.add(\"focused\");\n wrapper.classList.add(date_active);\n wrapper.setAttribute(date_lock, \"true\");\n window.setTimeout(clear_date_lock, 100);\n }\n\n const on_blur = function () {\n if (blur_cb !== undefined) {\n blur_cb();\n }\n wrapper.classList.remove(\"focused\");\n window.setTimeout(clear_date_active, 50);\n }\n\n const clear_date_active = function () {\n if (wrapper.getAttribute(date_lock) === \"true\") {\n return;\n }\n wrapper.classList.remove(date_active);\n }\n\n const clear_date_lock = function () {\n wrapper.removeAttribute(date_lock);\n }\n\n const date_val = function (values: DateValues): number {\n if (twelve_hour && values.period == Constants.period_pm && values.hour < 12) {\n values.hour += 12;\n }\n if (options.UTC) {\n return Date.UTC(values.year, values.month, values.day, values.hour, values.minute);\n }\n const d = new Date(values.year, values.month, values.day, values.hour, values.minute);\n return Number(d);\n }\n\n let first_d: HTMLDivElement;\n const month_d = viewNumberInput((month + 1), 1, 12, update, function (_: any) {\n last_d.focus();\n }, function (_: any) {\n day_d.focus();\n }, function (data: number) {\n const values = data_values();\n values.month = data - 1;\n const new_d = date_val(values);\n return new_d >= Number(d.getAttribute(data_min_key)) && new_d < Number(d.getAttribute(data_max_key));\n }, disabled, on_fucus, on_blur);\n\n const day_d = viewNumberInput(day, 1, month_day_counts[month], update, function (_: any) {\n month_d.focus();\n }, function (_: any) {\n year_d.focus();\n }, function (data: number) {\n const values = data_values();\n values.day = data;\n const new_d = date_val(values);\n return new_d >= Number(d.getAttribute(data_min_key)) && new_d < Number(d.getAttribute(data_max_key));\n }, disabled, on_fucus, on_blur);\n\n if (day_first) {\n first_d = day_d;\n } else {\n first_d = month_d;\n }\n\n const year_d = viewNumberInput(year, 1970, 2037, update, function (_: any) {\n day_d.focus();\n }, function (_: any) {\n hour_d.focus();\n }, function (data: number) {\n const values = data_values();\n values.year = data;\n const new_d = date_val(values);\n return new_d >= Number(d.getAttribute(data_min_key)) && new_d < Number(d.getAttribute(data_max_key));\n\n }, disabled, on_fucus, on_blur);\n\n const min_hour = twelve_hour ? 1 : 0;\n const max_hour = twelve_hour ? 12 : 23;\n const hour_d = viewNumberInput(hour, min_hour, max_hour, update, function (_: any) {\n year_d.focus();\n }, function (_: any) {\n minute_d.focus();\n }, function (data: number) {\n const values = data_values();\n values.hour = data;\n const new_d = date_val(values);\n return new_d >= Number(d.getAttribute(data_min_key)) && new_d < Number(d.getAttribute(data_max_key));\n }, disabled, on_fucus, on_blur);\n\n const minute_d = viewNumberInput(minute, 0, 59, update, function (_: any) {\n hour_d.focus();\n }, function (_: any) {\n if (twelve_hour) {\n am_pm_d.focus();\n } else {\n first_d.focus();\n }\n }, function (data: number) {\n const values = data_values();\n values.minute = data;\n const new_d = date_val(values);\n return new_d >= Number(d.getAttribute(data_min_key)) && new_d < Number(d.getAttribute(data_max_key));\n }, disabled, on_fucus, on_blur, true);\n\n const am_pm_d = viewDateAMPMInput(am_pm, update, function (_: any) {\n minute_d.focus();\n }, function (_: any) {\n first_d.focus();\n }, disabled, on_fucus, on_blur);\n\n const last_d = twelve_hour ? am_pm_d : minute_d;\n\n function data_values(): DateValues {\n let period = Constants.period_am;\n let data_period = am_pm_d.getAttribute(data_value_key);\n if (data_period) {\n period = data_period;\n }\n const vals = {\n month: Number(month_d.getAttribute(data_value_key)) - 1,\n day: Number(day_d.getAttribute(data_value_key)),\n year: Number(year_d.getAttribute(data_value_key)),\n hour: Number(hour_d.getAttribute(data_value_key)),\n minute: Number(minute_d.getAttribute(data_value_key)),\n period: period,\n };\n return vals;\n }\n\n let cal = div();\n\n const cal_cb = function (d: Date | null, t: InputCallbackType) {\n let new_date: Date | null = null;\n if (d) {\n const values = data_values();\n updateNumberInput(year_d, d.getFullYear(), false);\n updateNumberInput(month_d, d.getMonth() + 1, false);\n updateNumberInput(day_d, d.getDate(), false);\n new_date = new Date(d.getFullYear(), d.getMonth(), d.getDate(), values.hour, values.minute);\n }\n cb(new_date, t);\n }\n\n function update(t: InputCallbackType) {\n const values = data_values();\n if (values.day > month_day_counts[values.month]) {\n values.day = month_day_counts[values.month];\n day_d.setAttribute(data_value_key, String(values.day));\n day_d.innerHTML = String(values.day);\n }\n const max = month_day_counts[values.month];\n day_d.setAttribute(data_max_key, String(max));\n const new_date = new Date(date_val(values));\n if (options.ShowCalendar) {\n renderCalendar(cal, new_date, new_date, options, cal_cb);\n }\n cb(new_date, t);\n }\n\n month_d.classList.add(\"month\");\n day_d.classList.add(\"day\");\n year_d.classList.add(\"year\");\n hour_d.classList.add(\"hours\");\n minute_d.classList.add(\"minutes\");\n\n const s1 = span();\n s1.innerHTML = \"/\";\n const s2 = span();\n s2.innerHTML = \"/\";\n const s = span();\n const s3 = span();\n s3.innerHTML = \":\";\n if (day_first) {\n d.appendChild(day_d);\n } else {\n d.appendChild(month_d);\n }\n d.appendChild(s1);\n if (day_first) {\n d.appendChild(month_d);\n } else {\n d.appendChild(day_d);\n }\n d.appendChild(s2);\n d.appendChild(year_d);\n if (options.Type === DatePickerType.DateTime) {\n d.appendChild(s);\n d.appendChild(hour_d);\n d.appendChild(s3);\n d.appendChild(minute_d);\n if (twelve_hour) {\n d.appendChild(s);\n d.appendChild(am_pm_d);\n }\n }\n\n const pad = function (i: number): string {\n return (i < 10 ? '0' : '') + i;\n }\n\n const YYYY = date.getFullYear();\n const MM = pad(date.getMonth() + 1);\n const DD = pad(date.getDate());\n const HH = pad(date.getHours());\n const II = pad(date.getMinutes());\n let date_str = \"\";\n\n const datetime = document.createElement(\"input\");\n if (options.Type === DatePickerType.DateTime) {\n datetime.setAttribute(\"type\", \"datetime-local\");\n date_str = YYYY + '-' + MM + '-' + DD + 'T' + HH + ':' + II;\n } else {\n datetime.setAttribute(\"type\", \"date\");\n date_str = YYYY + '-' + MM + '-' + DD;\n }\n datetime.value = date_str;\n datetime.min = min.toUTCString();\n datetime.max = max.toUTCString();\n datetime.setAttribute(\"default\", date_str);\n\n datetime.onchange = function () {\n if (datetime.value.length == 0) {\n const default_date = datetime.getAttribute(\"default\");\n if (default_date) {\n datetime.value = default_date;\n }\n }\n\n // datetime-local returns dates in the format: \"2019-06-17T18:07\"\n const parts = datetime.value.split(\"T\");\n const date_parts = parts[0].split(\"-\");\n const new_date = new Date();\n const year = Number(date_parts[0]);\n const month = Number(date_parts[1]) - 1;\n const day = Number(date_parts[2]);\n new_date.setFullYear(year);\n new_date.setMonth(month);\n new_date.setDate(day);\n new_date.setHours(0);\n new_date.setMinutes(0);\n new_date.setSeconds(0);\n new_date.setMilliseconds(0);\n if (options.Type === DatePickerType.DateTime) {\n const time_parts = parts[1].split(\":\");\n const hour = Number(time_parts[0]);\n const minute = Number(time_parts[1]);\n new_date.setHours(hour);\n new_date.setMinutes(minute);\n }\n cb(new_date, InputCallbackType.Change);\n }\n\n wrapper.appendChild(d);\n wrapper.appendChild(datetime);\n\n if (options.ShowCalendar) {\n cal = viewCalendarInput(date, options, cal_cb);\n wrapper.appendChild(cal);\n cal.tabIndex = -1;\n\n cal.addEventListener(\"focus\", function () {\n wrapper.classList.add(\"focused\");\n wrapper.setAttribute(date_lock, \"true\");\n window.setTimeout(clear_date_lock, 100);\n });\n\n cal.addEventListener(\"blur\", function () {\n wrapper.classList.remove(\"focused\");\n window.setTimeout(clear_date_active, 50);\n });\n }\n\n return wrapper;\n}\n", "import { App, BQData } from \"./app\";\nimport { BQ } from \"./bq\";\nimport { SVG } from \"../../shared/svg\";\nimport { Api, UpdateOpts } from \"./api\";\nimport { Editor, SelectVal } from \"./editor\";\nimport { div, input, span, anchor } from \"../../shared/dom\";\nimport { Loading } from \"../../shared/loading\";\nimport * as CodeMirror from 'codemirror';\nimport { ApiAttribute, ApiDisplayUpdate, ApiPageUpdate, ApiUpdate } from \"./api_data\";\nimport { TablePicker } from \"./table_picker\";\nimport { Display, DataConnection, FilterConnection } from \"./display\";\nimport { VizSVG } from \"./viz_svg\";\nimport { Menu } from \"../../shared/menu\";\nimport { Page, VizConnection } from \"./page\";\nimport { Ajax } from \"../../shared/ajax\";\nimport { DateInputOptions, viewDatePicker, DatePickerType } from \"../../shared/date_picker\";\nimport { InputCallbackType } from \"../../shared/input_callback\";\n\ninterface DisplayNode {\n viz: VizConnection,\n group: string;\n position: number,\n element: SVGGElement,\n x: number,\n y: number,\n height: number,\n}\n\ninterface DisplaySpacer {\n group: string;\n position: number,\n element: SVGRectElement,\n}\n\ninterface SelectRow {\n container: HTMLElement;\n label_container: HTMLElement;\n val_container: HTMLElement;\n select: HTMLSelectElement;\n}\n\nexport class EditorPage {\n\n static render_table(page: Page, viz: Display): HTMLTableElement {\n const table = document.createElement(\"table\");\n const t_head = document.createElement(\"thead\");\n const t_head_row = document.createElement(\"tr\");\n t_head.appendChild(t_head_row);\n table.appendChild(t_head);\n if (viz.query_columns.length > 0) {\n const th = document.createElement(\"th\");\n th.classList.add(\"idx\");\n t_head_row.appendChild(th);\n }\n\n const render_header = function (col: BQData) {\n const th = document.createElement(\"th\");\n if (page.selected_element === col.column_name) {\n th.classList.add(\"active\");\n }\n let p_label = col.pivot ? \".\" + col.pivot : \"\";\n if (col.pivot_target) {\n p_label += \" \" + col.pivot_target;\n }\n th.innerText = col.column_name + p_label;\n t_head_row.appendChild(th);\n }\n\n for (const col of viz.query_columns) {\n if (BQ.skip_col(col)) {\n continue;\n }\n render_header(col);\n }\n\n let selected_key = \"\";\n const selected_col = Editor.get_selected_column(page);\n if (selected_col) {\n selected_key = Editor.data_key(selected_col.data, true);\n }\n if (viz.query_columns.length > 0) {\n let row_count = 0;\n for (const col of viz.data) {\n row_count = Math.max(row_count, col.rows.length);\n }\n for (let i = 0; i < row_count; i++) {\n const tr = document.createElement(\"tr\");\n const index_td = document.createElement(\"td\");\n index_td.classList.add(\"idx\");\n index_td.innerText = (i + 1).toString();\n tr.appendChild(index_td);\n for (const col of viz.query_columns) {\n const k = Editor.data_key(col, true);\n if (BQ.skip_col(col)) {\n continue;\n }\n const td = document.createElement(\"td\");\n if (selected_key === k) {\n td.classList.add(\"active\");\n }\n for (const data_col of viz.data) {\n if (Editor.data_key(col, true) === Editor.data_key(data_col, true)) {\n if (data_col.rows.length > i) {\n const row = data_col.rows[i];\n td.innerText = row;\n }\n }\n }\n tr.appendChild(td);\n }\n table.appendChild(tr);\n }\n }\n return table;\n }\n\n static init_data_dom(page: Page, bottom: HTMLElement) {\n const title = div(\"section-title\");\n const selector = div(\"selector\");\n const data = div(\"option\");\n data.innerText = \"Data\";\n const sql = div(\"option\");\n sql.innerText = \"SQL\";\n selector.appendChild(data);\n selector.appendChild(sql);\n title.appendChild(selector);\n\n title.appendChild(div(\"spacer\"));\n\n const toggle_selector = div(\"selector\");\n const toggle = VizSVG.bottom_panel_icon();\n toggle_selector.appendChild(toggle);\n title.appendChild(toggle_selector);\n\n const set_selector_state = function () {\n if (page.show_query) {\n data.classList.remove(\"selected\");\n sql.classList.add(\"selected\");\n } else {\n data.classList.add(\"selected\");\n sql.classList.remove(\"selected\");\n }\n }\n if (page.data_panel_open) {\n set_selector_state();\n }\n\n const set_toggle_state = function (val: boolean) {\n Editor.set_data_panel_open(page, val);\n const editor = document.querySelector(\"div.editor\");\n if (!editor) {\n return;\n }\n if (val) {\n editor.classList.add(\"data-open\");\n set_selector_state();\n } else {\n editor.classList.remove(\"data-open\");\n data.classList.remove(\"selected\");\n sql.classList.remove(\"selected\");\n }\n }\n\n toggle.onclick = function () {\n const val = !page.data_panel_open;\n set_toggle_state(val);\n }\n\n data.onclick = function () {\n page.show_query = false;\n set_selector_state();\n if (!page.data_panel_open) {\n set_toggle_state(true);\n }\n App.render();\n }\n\n sql.onclick = function () {\n page.show_query = true;\n set_selector_state();\n if (!page.data_panel_open) {\n set_toggle_state(true);\n }\n App.render();\n }\n\n const loading = Loading.overlay()\n loading.style.display = \"none\";\n\n bottom.appendChild(title);\n\n const content = div(\"content\");\n\n const table_container = div(\"table-container\");\n content.appendChild(table_container);\n\n const query_container = div(\"query-container\");\n const area = document.createElement(\"textarea\");\n query_container.appendChild(area);\n content.appendChild(query_container);\n\n content.appendChild(loading);\n bottom.appendChild(content);\n\n console.log(\"init editor\");\n Editor.editor = CodeMirror.fromTextArea(area, {\n mode: \"text/x-sql\",\n lineNumbers: true,\n readOnly: true,\n });\n\n }\n\n static render_data(page: Page, viz: Display | null, bottom: HTMLElement) {\n\n if (!bottom.querySelector(\"div.content\")) {\n EditorPage.init_data_dom(page, bottom);\n }\n\n const table_container = bottom.querySelector(\"div.table-container\") as HTMLElement;\n const query_container = bottom.querySelector(\"div.query-container\") as HTMLElement;\n if (!table_container || !query_container || !Editor.editor || !page) {\n return;\n }\n\n if (page.show_query) {\n table_container.style.display = \"none\";\n query_container.style.display = \"block\";\n } else {\n table_container.style.display = \"block\";\n query_container.style.display = \"none\";\n }\n\n table_container.innerHTML = \"\";\n Editor.editor.setValue(\"\");\n if (!viz) {\n return;\n }\n\n const table = EditorPage.render_table(page, viz);\n table_container.appendChild(table);\n\n Editor.editor.setValue(BQ.build_query(viz));\n }\n\n static add_icon(el: HTMLElement, col_type: string) {\n switch (col_type) {\n case \"INTEGER\":\n case \"INT64\":\n case \"FLOAT64\":\n el.appendChild(VizSVG.number_icon())\n break;\n\n case \"DATE\":\n case \"TIMESTAMP\":\n el.appendChild(VizSVG.date_icon())\n break;\n\n case \"STRING\":\n el.appendChild(VizSVG.text_icon())\n break;\n\n default:\n break;\n }\n }\n\n /* TODO: needed?\n static render_picker(container: HTMLElement, selected_set: DataConnection[], filter: ColumnFilter, search: string, cb: Function) {\n container.innerHTML = \"\";\n if (!VizApp.selected_viz || !VizApp.selected_viz.selected_table) {\n return;\n }\n container.onmousedown = function () {\n container.setAttribute(\"locked\", \"true\");\n window.setTimeout(function () {\n container.removeAttribute(\"locked\");\n }, 50);\n }\n for (const col of VizApp.selected_viz.selected_table.table.columns) {\n if (filter === ColumnFilter.NumericOnly && !BQ.numeric_col(col.type)) {\n continue;\n }\n if (search !== \"\") {\n const match = col.name.toLowerCase().indexOf(search.toLowerCase()) === 0;\n if (!match) {\n continue;\n }\n }\n const col_el = div(\"view-element\");\n col_el.innerText = col.name;\n EditorPage.add_icon(col_el, col.type);\n container.appendChild(col_el);\n\n let selected = false;\n for (const sel of selected_set) {\n if (sel.data.column_name === col.name && sel.data.table_id === col.table_id) {\n selected = true;\n }\n }\n if (selected) {\n col_el.classList.add(\"disabled\");\n } else {\n col_el.classList.add(\"enabled\");\n }\n\n if (!selected) {\n col_el.onclick = function () {\n cb(col);\n }\n }\n }\n }*/\n\n private static render_viz_list(page: Page, viz_list: Display[], container: HTMLElement) {\n\n const render = function (viz: Display) {\n const viz_el = div(\"view-element\", \"parent-element\");\n viz_el.id = \"viz_\" + viz.id;\n const s = span();\n s.innerText = viz.title;\n viz_el.appendChild(s);\n viz_el.appendChild(VizSVG.display_icon());\n if (page.selected_element === viz.id) {\n viz_el.classList.add(\"selected\");\n }\n container.appendChild(viz_el);\n const viz_arrow = div(\"arrow-wrapper\");\n viz_arrow.appendChild(VizSVG.arrow());\n viz_el.appendChild(viz_arrow);\n viz_arrow.onmousedown = function (e) {\n e.stopPropagation();\n Editor.set_viz_closed(viz, !viz.closed);\n App.render();\n }\n\n viz_el.onclick = function (e) {\n e.stopPropagation();\n }\n\n viz_el.onmousedown = function (e) {\n Editor.set_selected_element(viz.id);\n e.stopPropagation();\n App.render();\n }\n\n if (viz.closed) {\n viz_el.classList.add(\"closed\");\n return;\n }\n\n const table_el = div(\"view-element\", \"group-element\");\n if (viz.selected_table) {\n const l = span(\"element-label\");\n l.innerText = viz.selected_table.table.id;\n table_el.appendChild(l);\n } else {\n table_el.innerText = \"Select table...\";\n }\n table_el.appendChild(VizSVG.table_icon());\n container.appendChild(table_el);\n\n const table_arrow = div(\"arrow-wrapper\");\n table_arrow.appendChild(VizSVG.arrow());\n table_el.appendChild(table_arrow);\n table_arrow.onmousedown = function (e) {\n if (!viz.selected_table) {\n return;\n }\n e.stopPropagation();\n Editor.set_table_closed(viz, !viz.selected_table.closed);\n App.render();\n }\n\n table_el.onclick = function (e) {\n e.stopPropagation();\n }\n\n table_el.onmousedown = function (e) {\n e.stopPropagation();\n if (viz.selected_table) {\n Editor.set_selected_element(viz.selected_table.id);\n App.render();\n } else {\n TablePicker.render_overlay(page, viz, viz.selected_table);\n }\n }\n\n if (viz.selected_table && page.selected_element === viz.selected_table.id) {\n table_el.classList.add(\"selected\");\n }\n\n if (viz.selected_table) {\n const menu = Menu.menu();\n table_el.appendChild(menu.container);\n Menu.add_menu_item(menu, \"Replace Table\", function () {\n TablePicker.render_overlay(page, viz, viz.selected_table);\n })\n table_el.id = \"table_\" + viz.selected_table.id;\n }\n\n if (viz.selected_table && viz.selected_table.closed) {\n table_el.classList.add(\"closed\");\n return;\n }\n\n if (viz.selected_table === null) {\n return;\n }\n\n let selected_id = \"\";\n // try the selected_element directly, which will work for count\n if (App.selected_page && App.selected_page.selected_element) {\n selected_id = App.selected_page.selected_element;\n }\n const selected_col = Editor.get_selected_column(page);\n if (selected_col) {\n selected_id = viz.selected_table?.id + \":\" + selected_col.id;\n }\n let subs_closed = false;\n for (const sel of viz.selected_columns) {\n if (sel.data.pivoted) {\n subs_closed = sel.data.closed;\n }\n if (subs_closed && sel.data.pivot) {\n continue;\n }\n const col_el = div(\"view-element\");\n col_el.id = \"con_\" + sel.id;\n if (sel.data.pivot) {\n col_el.innerText = sel.data.pivot;\n col_el.classList.add(\"sub-element\");\n } else {\n col_el.innerText = sel.data.column_name;\n }\n const vis = div(\"visibility\");\n vis.appendChild(VizSVG.visibility_icon());\n col_el.appendChild(vis);\n if (sel.data.hidden) {\n col_el.classList.add(\"hidden\");\n }\n vis.onmousedown = function (e) {\n e.stopPropagation();\n Editor.set_visibility(viz, sel, !sel.data.hidden);\n }\n EditorPage.add_icon(col_el, sel.data.column_type);\n\n const id = viz.selected_table?.id + \":\" + sel.id;\n if (id === selected_id) {\n col_el.classList.add(\"selected\");\n }\n\n col_el.onclick = function (e) {\n e.stopPropagation();\n }\n\n col_el.onmousedown = function (e) {\n Editor.set_selected_element(id);\n e.stopPropagation();\n App.render();\n }\n\n container.appendChild(col_el);\n\n if (sel.data.pivoted) {\n let all_subs_hidden = true;\n const key = Editor.data_key(sel.data, false);\n for (const s of viz.selected_columns) {\n if (s.data.pivoted) {\n continue;\n }\n const k = Editor.column_key(s.data.dataset_id, s.data.table_id, s.data.column_name, null);\n if (k === key && s.data.hidden == false) {\n all_subs_hidden = false;\n break;\n }\n }\n if (all_subs_hidden) {\n col_el.classList.add(\"hidden\");\n }\n const vis = div(\"visibility\");\n vis.appendChild(VizSVG.visibility_icon());\n col_el.appendChild(vis);\n vis.onmousedown = function (e) {\n e.stopPropagation();\n const new_val = !all_subs_hidden;\n Editor.set_pivot_sub_values_visibility(viz, sel, new_val);\n }\n\n const arrow = div(\"arrow-wrapper\");\n arrow.appendChild(VizSVG.arrow());\n col_el.appendChild(arrow);\n arrow.onmousedown = function (e) {\n e.stopPropagation();\n Editor.set_pivot_closed(viz, sel, !sel.data.closed);\n App.render();\n }\n if (sel.data.closed) {\n col_el.classList.add(\"closed\");\n }\n }\n }\n\n const count_id = viz.selected_table?.id + \":count\";\n const count_el = div(\"view-element\");\n count_el.id = count_id;\n count_el.innerText = \"Count\";\n container.appendChild(count_el);\n const vis = div(\"visibility\");\n vis.appendChild(VizSVG.visibility_icon());\n count_el.appendChild(vis);\n vis.onmousedown = function (e) {\n e.stopPropagation();\n Editor.set_count_visibility(viz, !viz.count.hidden);\n }\n if (viz.count.hidden) {\n count_el.classList.add(\"hidden\");\n }\n\n EditorPage.add_icon(count_el, \"INTEGER\");\n if (count_id === selected_id) {\n count_el.classList.add(\"selected\");\n }\n\n count_el.onclick = function (e) {\n e.stopPropagation();\n }\n\n count_el.onmousedown = function (e) {\n Editor.set_selected_element(count_el.id);\n e.stopPropagation();\n App.render();\n }\n\n // TODO: remove?\n const show_add_col = false;\n if (show_add_col) {\n const add = div(\"view-element\", \"add-element\");\n const add_input = App.input();\n add_input.placeholder = \"Add Column\";\n\n const show_picker = function () {\n /*if (!VizApp.selected_viz) {\n return;\n }*/\n add.classList.add(\"active\");\n picker.style.display = \"block\";\n /*EditorPage.render_picker(picker, VizApp.selected_viz.selected_columns, ColumnFilter.NoFilter, \"\", function (col: ApiBQCol) {\n Editor.add_column(viz, col);\n });*/\n }\n\n const hide_picker = function () {\n if (picker.getAttribute(\"locked\") === \"true\") {\n return;\n }\n add.classList.remove(\"active\");\n picker.style.display = \"none\";\n }\n\n add_input.addEventListener('focus', function () {\n show_picker();\n });\n\n add_input.addEventListener('blur', function () {\n hide_picker();\n });\n\n add_input.oninput = function () {\n /*if (!VizApp.selected_viz) {\n return;\n }\n EditorPage.render_picker(picker, VizApp.selected_viz.selected_columns, ColumnFilter.NoFilter, add_input.value, function (col: ApiBQCol) {\n Editor.add_column(viz, col);\n });*/\n }\n const plus = VizSVG.plus_icon();\n plus.classList.add(\"add-icon\");\n add.appendChild(plus);\n container.appendChild(add);\n\n add.appendChild(add_input);\n\n const picker = div(\"element-picker\");\n add.onclick = function (e) {\n e.stopPropagation();\n add_input.focus();\n }\n\n add.appendChild(picker);\n picker.style.display = \"none\";\n }\n }\n\n for (const viz of viz_list) {\n render(viz);\n }\n }\n\n static render_left_rail(container: HTMLElement) {\n const d = div();\n container.appendChild(d);\n\n const col_container = div();\n d.appendChild(col_container);\n\n const viz_list: Display[] = [];\n if (App.selected_page) {\n for (const conn of App.selected_page.viz_list) {\n viz_list.push(conn.viz);\n }\n }\n\n container.onclick = function () {\n Editor.set_selected_element(null);\n App.render();\n }\n\n if (!App.selected_page) {\n return;\n }\n\n EditorPage.render_viz_list(App.selected_page, viz_list, col_container);\n\n /* TODO: remove?\n const info_row = function (label: string, val: string): HTMLElement {\n const row = div(\"panel-row\");\n const date_label = div(\"label\");\n date_label.innerText = label;\n const date_val = div();\n date_val.innerText = val;\n row.appendChild(date_label);\n row.appendChild(date_val);\n return row;\n }\n\n const table_info = div(\"table-info\");\n const table_title = div(\"section-title\");\n table_title.innerText = \"Table Info\";\n table_info.appendChild(table_title);\n const date = new Date(viz.selected_table.table.creation_time);\n table_info.appendChild(info_row(\"Created\", date.toLocaleDateString()));\n table_info.appendChild(info_row(\"Rows\", viz.selected_table.table.row_count.toString()));\n d.appendChild(table_info);*/\n\n }\n\n static select_row(label: string, selection: string, opts: SelectVal[]): SelectRow {\n const row = div(\"panel-row\");\n const label_el = div(\"label\");\n label_el.innerText = label;\n const val = div(\"value\");\n const sel = document.createElement(\"select\");\n sel.style.backgroundImage = \"url(\" + SVG.to_url(SVG.chevron()) + \")\";\n for (const opt of opts) {\n const o = document.createElement(\"option\");\n if (opt.value === selection) {\n o.selected = true;\n }\n o.value = opt.value;\n o.innerText = opt.label;\n sel.appendChild(o);\n }\n val.appendChild(sel);\n row.appendChild(label_el);\n row.appendChild(val);\n return {\n container: row,\n label_container: label_el,\n val_container: val,\n select: sel,\n }\n }\n\n static date_col_opts(viz: Display): SelectVal[] {\n let date_opts: SelectVal[] = [];\n for (const c of viz.selected_columns) {\n if (BQ.date_col(c.data.column_type)) {\n const v = {\n label: c.data.column_name,\n value: c.data.column_name,\n }\n date_opts.push(v);\n }\n }\n return date_opts;\n }\n\n static string_col_opts(viz: Display): SelectVal[] {\n let opts: SelectVal[] = [];\n for (const c of viz.selected_columns) {\n if (c.data.column_type === \"STRING\") {\n const v = {\n label: c.data.column_name,\n value: c.data.column_name,\n }\n opts.push(v);\n }\n }\n return opts;\n }\n\n static render_date_filter_settings(viz: Display, f: FilterConnection, container: HTMLElement) {\n\n const types = [Editor.date_recent, Editor.date_current, Editor.date_custom];\n const type_row = EditorPage.select_row(\"Range\", f.date_mode, types);\n container.appendChild(type_row.container);\n\n type_row.select.onchange = function () {\n f.date_mode = type_row.select.value;\n Editor.update_filter(viz, f);\n }\n\n if (f.date_mode === Editor.date_recent.value || f.date_mode === Editor.date_current.value) {\n const selected = f.date_mode === Editor.date_recent.value ? f.date_recent_interval : f.date_current_interval;\n const vals = f.date_mode === Editor.date_recent.value ? Editor.date_groups_plural : Editor.date_groups;\n const int_row = EditorPage.select_row(\"Interval\", selected, vals);\n container.appendChild(int_row.container);\n\n const i_inp = App.input();\n i_inp.value = f.date_recent_count.toString();\n\n if (f.date_mode === Editor.date_recent.value) {\n int_row.val_container.classList.add(\"value-flex\");\n int_row.val_container.insertBefore(i_inp, int_row.val_container.firstChild);\n }\n\n const update_count = function () {\n const n = Number(i_inp.value);\n if (isNaN(n)) {\n return;\n }\n f.date_recent_count = n;\n Editor.update_filter(viz, f);\n }\n\n i_inp.onchange = function () {\n update_count();\n }\n\n i_inp.onkeydown = function (e) {\n if (e.code === \"Enter\") {\n update_count();\n }\n };\n\n int_row.select.onchange = function () {\n if (f.date_mode === Editor.date_recent.value) {\n f.date_recent_interval = int_row.select.value;\n } else {\n f.date_current_interval = int_row.select.value;\n }\n Editor.update_filter(viz, f);\n }\n } else {\n\n const date_row = function (label: string, date_str: string | null, default_date: Date, cb: Function) {\n const r = div(\"panel-row\");\n const label_el = div(\"label\");\n label_el.innerText = label;\n const val = div(\"value\");\n r.appendChild(label_el);\n r.appendChild(val);\n\n const date_picker = div(\"date-picker\");\n date_picker.style.backgroundImage = \"url(\" + SVG.to_url(SVG.chevron()) + \")\";\n\n const auto_enabled = false;\n const min = new Date(Date.UTC(1970, 1));\n const max = new Date(Date.UTC(2037, 1));\n const opts: DateInputOptions = {\n UTC: false,\n Force24Hour: false,\n ShowCalendar: true,\n Type: DatePickerType.Date,\n ShowClear: true,\n };\n\n const date = date_str ? new Date(date_str) : default_date;\n const picker = viewDatePicker(date, min, max, auto_enabled, function (d: Date | null, t: InputCallbackType) {\n if (!d) {\n picker.style.display = \"none\";\n }\n cb(d, t);\n }, opts);\n date_picker.appendChild(picker);\n val.appendChild(date_picker);\n\n if (!date_str) {\n picker.style.display = \"none\";\n }\n\n let date_chevron_cancel = false;\n date_picker.onclick = function () {\n if (date_chevron_cancel) {\n return;\n }\n if (picker.style.display === \"none\") {\n cb(date, InputCallbackType.Enter);\n }\n picker.style.display = \"block\";\n\n const first_el = r.querySelector(\"div.date-selector div\") as HTMLElement;\n if (first_el) {\n first_el.focus();\n }\n }\n\n date_picker.onmousedown = function () {\n const selector = r.querySelector(\"div.date-selector-wrapper\");\n if (selector && selector.classList.contains(\"focused\")) {\n date_chevron_cancel = true;\n } else {\n date_chevron_cancel = false;\n }\n }\n return r;\n }\n\n const date_str = function (d: Date): string {\n return d.getFullYear() + \"-\" + (d.getMonth() + 1) + \"-\" + d.getDate();\n }\n\n let s_default = new Date();\n s_default.setMonth(s_default.getMonth() - 1);\n const s = date_row(\"Start\", f.date_min, s_default, function (d: Date | null, _t: InputCallbackType) {\n console.log(d);\n let val: string | null = null;\n if (d) {\n val = date_str(d);\n }\n f.date_min = val;\n Editor.update_filter(viz, f);\n });\n container.appendChild(s);\n\n const e_default = new Date();\n const e = date_row(\"End\", f.date_max, e_default, function (d: Date | null, _t: InputCallbackType) {\n console.log(d);\n let val: string | null = null;\n if (d) {\n val = date_str(d);\n }\n f.date_max = val;\n Editor.update_filter(viz, f);\n });\n container.appendChild(e);\n }\n }\n\n static render_text_filter_settings(viz: Display, f: FilterConnection, container: HTMLElement) {\n\n const vals = [Editor.text_match, Editor.text_not_match];\n const match_row = EditorPage.select_row(\"Match\", f.text_mode, vals);\n container.appendChild(match_row.container);\n\n const val_row = EditorPage.select_row(\"Value\", \"\", []);\n val_row.val_container.innerHTML = \"\";\n const inp = App.input();\n if (f.text_query) {\n inp.value = f.text_query;\n }\n val_row.val_container.appendChild(inp);\n container.appendChild(val_row.container);\n\n inp.onchange = function () {\n f.text_query = inp.value;\n Editor.update_filter(viz, f);\n }\n }\n\n static render_filter(viz: Display, container: HTMLElement) {\n const section = div(\"section\");\n const title = div(\"section-title\", \"first-section\");\n title.innerText = \"Filter\";\n section.appendChild(title);\n\n let col_opts: SelectVal[] = [];\n for (const c of viz.selected_columns) {\n if (BQ.date_col(c.data.column_type) || c.data.column_type === \"STRING\") {\n const v = {\n label: c.data.column_name,\n value: c.data.column_name,\n }\n col_opts.push(v);\n }\n }\n\n for (const f of viz.filters) {\n\n const f_el = div(\"filter\");\n const col_row = EditorPage.select_row(\"Column\", f.column, col_opts);\n f_el.appendChild(col_row.container);\n const minus = VizSVG.minus();\n minus.onclick = function () {\n Editor.remove_filter(viz, f);\n }\n col_row.label_container.appendChild(minus);\n col_row.select.onchange = function () {\n f.column = col_row.select.value;\n Editor.update_filter(viz, f);\n }\n\n // get matching the col\n let col: BQData | null = null;\n for (const c of viz.selected_columns) {\n if (c.data.column_name === f.column) {\n col = c.data;\n break;\n }\n }\n\n if (col) {\n if (BQ.date_col(col.column_type)) {\n EditorPage.render_date_filter_settings(viz, f, f_el);\n } else {\n EditorPage.render_text_filter_settings(viz, f, f_el);\n }\n }\n\n section.appendChild(f_el);\n }\n\n const plus = VizSVG.plus();\n plus.onclick = function () {\n if (col_opts.length > 0) {\n Editor.add_filter(viz, col_opts[0].value);\n }\n }\n title.appendChild(plus);\n container.appendChild(section);\n }\n\n static render_group(viz: Display, container: HTMLElement) {\n const section = div(\"section\");\n const group_title = div(\"section-title\", \"first-section\");\n group_title.innerText = \"Group By\";\n section.appendChild(group_title);\n\n let date_opts = EditorPage.date_col_opts(viz);\n\n if (viz.group_by) {\n\n const selected = viz.group_by ? viz.group_by : \"\";\n const group_row = EditorPage.select_row(\"Column\", selected, date_opts);\n section.appendChild(group_row.container);\n\n group_row.select.onchange = function () {\n Editor.set_group_by(viz, group_row.select.value, int_row.select.value);\n }\n\n const selected_int = viz.group_by_interval ? viz.group_by_interval : \"\";\n const int_row = EditorPage.select_row(\"Interval\", selected_int, Editor.date_groups);\n section.appendChild(int_row.container);\n\n int_row.select.onchange = function () {\n Editor.set_group_by(viz, group_row.select.value, int_row.select.value);\n }\n }\n\n if (viz.group_by) {\n const minus = VizSVG.minus();\n minus.onclick = function () {\n Editor.set_group_by(viz, null, null);\n }\n group_title.appendChild(minus);\n\n } else {\n const plus = VizSVG.plus();\n plus.onclick = function () {\n if (date_opts.length > 0) {\n Editor.set_group_by(viz, date_opts[0].value, Editor.date_groups[0].value);\n }\n }\n group_title.appendChild(plus);\n }\n container.appendChild(section);\n }\n\n static render_sort(viz: Display, container: HTMLElement) {\n const section = div(\"section\");\n const title = div(\"section-title\", \"first-section\");\n title.innerText = \"Sort\";\n section.appendChild(title);\n\n let date_opts = EditorPage.date_col_opts(viz);\n\n if (viz.sort) {\n const selected = viz.sort ? viz.sort : \"\";\n const sort_row = EditorPage.select_row(\"Column\", selected, date_opts);\n section.appendChild(sort_row.container);\n\n sort_row.select.onchange = function () {\n Editor.set_sort(viz, sort_row.select.value, order_row.select.value);\n }\n\n const sort_selected = viz.sort_order ? viz.sort_order : \"\";\n const order_row = EditorPage.select_row(\"Order\", sort_selected, Editor.sort_orders);\n section.appendChild(order_row.container);\n\n order_row.select.onchange = function () {\n Editor.set_sort(viz, sort_row.select.value, order_row.select.value);\n }\n }\n\n if (viz.sort) {\n const minus = VizSVG.minus();\n minus.onclick = function () {\n Editor.set_sort(viz, null, null);\n }\n title.appendChild(minus);\n\n } else {\n const plus = VizSVG.plus();\n plus.onclick = function () {\n if (viz.selected_columns.length === 0) {\n return;\n }\n const column_name = date_opts.length > 0 ? date_opts[0].value : viz.selected_columns[0].data.column_name;\n Editor.set_sort(viz, column_name, Editor.sort_orders[0].value);\n }\n title.appendChild(plus);\n }\n container.appendChild(section);\n }\n\n static render_pivot_opts(display: Display, col: DataConnection, container: HTMLElement) {\n const is_date = BQ.date_col(col.data.column_type);\n if (is_date) {\n const facet_row = div(\"panel-row\");\n const facet_label = div(\"label\");\n facet_label.innerText = \"Facet\";\n const facet_val = div(\"value\");\n const facet_sel = document.createElement(\"select\");\n facet_sel.style.backgroundImage = \"url(\" + SVG.to_url(SVG.chevron()) + \")\";\n facet_val.appendChild(facet_sel);\n facet_row.appendChild(facet_label);\n facet_row.appendChild(facet_val);\n container.appendChild(facet_row);\n\n for (const opt of Editor.date_pivots) {\n const o = document.createElement(\"option\");\n if (col.data.pivot_facet === opt) {\n o.selected = true;\n }\n o.value = opt;\n o.innerText = opt;\n facet_sel.appendChild(o);\n }\n }\n\n const row = div(\"panel-row\");\n const label = div(\"label\");\n label.innerText = \"Measure\";\n const val = div(\"value\");\n const sel = document.createElement(\"select\");\n sel.style.backgroundImage = \"url(\" + SVG.to_url(SVG.chevron()) + \")\";\n\n const count = document.createElement(\"option\");\n if (!col.data.pivot_op) {\n count.selected = true;\n }\n count.value = \"Count\";\n count.innerText = \"Count\";\n sel.appendChild(count);\n\n const sum = document.createElement(\"option\");\n if (col.data.pivot_op) {\n sum.selected = true;\n }\n sum.value = \"Sum\";\n sum.innerText = \"Sum\";\n sel.appendChild(sum);\n\n val.appendChild(sel);\n\n sel.onchange = function () {\n if (sel.value === \"Count\") {\n Editor.set_pivot_op(display, col, null);\n } else {\n Editor.set_pivot_op(display, col, \"SUM\");\n Editor.add_pivot_measure(display, col);\n }\n }\n\n row.appendChild(label);\n row.appendChild(val);\n container.appendChild(row);\n\n if (col.data.pivot_op) {\n for (const measure of col.data.pivot_measures) {\n const r = div(\"panel-row\");\n const l = div(\"label\");\n l.innerText = \"Column\";\n const v = div(\"value\");\n const s = document.createElement(\"select\");\n\n s.style.backgroundImage = \"url(\" + SVG.to_url(SVG.chevron()) + \")\";\n\n if (display.selected_table && display.selected_table.table.columns) {\n for (const c of display.selected_table.table.columns) {\n if (!BQ.numeric_col(c.type)) {\n continue;\n }\n const op = document.createElement(\"option\");\n if (c.name === measure.column) {\n op.selected = true;\n }\n for (const m of col.data.pivot_measures) {\n if (m.column === c.name && m !== measure) {\n op.disabled = true\n }\n }\n op.value = c.name;\n op.innerText = c.name;\n s.appendChild(op);\n }\n }\n\n s.onchange = function () {\n Editor.update_pivot_measure(display, col, measure, s.value);\n }\n\n v.appendChild(s);\n r.appendChild(l);\n r.appendChild(v);\n container.appendChild(r);\n }\n }\n }\n\n static render_pivot(page: Page, display: Display, container: HTMLElement) {\n const selected_col = Editor.get_selected_column(page);\n if (!selected_col || !display.selected_table) {\n return;\n }\n const pivot = div(\"section\");\n const pivot_title = div(\"section-title\");\n pivot_title.innerText = \"Pivot\";\n pivot.appendChild(pivot_title);\n container.appendChild(pivot);\n\n // pivot is for date or string\n const is_string = selected_col.data.column_type === \"STRING\";\n const is_date = BQ.date_col(selected_col.data.column_type);\n if (!is_date && !is_string) {\n pivot.classList.add(\"disabled\");\n }\n\n if (selected_col.data.pivoted) {\n const minus = VizSVG.minus();\n minus.onclick = function () {\n Editor.remove_pivot(selected_col);\n }\n pivot_title.appendChild(minus);\n //if (is_string) {\n EditorPage.render_pivot_opts(display, selected_col, pivot);\n //}\n } else {\n const plus = VizSVG.plus();\n if ((is_string || is_date) && !selected_col.data.pivot) {\n plus.onclick = function () {\n Editor.add_pivot(display, selected_col);\n }\n }\n pivot_title.appendChild(plus);\n }\n }\n\n static render_operation(page: Page, viz: Display, container: HTMLElement) {\n const selected_col = Editor.get_selected_column(page);\n if (!selected_col) {\n return;\n }\n\n const section = div(\"section\");\n const op_title = div(\"section-title\");\n op_title.innerText = \"Operation\";\n section.appendChild(op_title);\n\n // op is currently number only\n if (!BQ.numeric_col(selected_col.data.column_type)) {\n section.classList.add(\"disabled\");\n }\n\n if (selected_col.data.operation) {\n const minus = VizSVG.minus();\n minus.onclick = function () {\n Editor.set_operation(viz, selected_col, null);\n }\n op_title.appendChild(minus);\n\n const op_row = EditorPage.select_row(\"Measure\", selected_col.data.operation, Editor.operations);\n section.appendChild(op_row.container);\n\n op_row.select.onchange = function () {\n Editor.set_operation(viz, selected_col, op_row.select.value);\n }\n } else {\n const plus = VizSVG.plus();\n plus.onclick = function () {\n if (!selected_col || !BQ.numeric_col(selected_col.data.column_type)) {\n return;\n }\n Editor.set_operation(viz, selected_col, Editor.operations[0].value);\n }\n op_title.appendChild(plus);\n }\n container.appendChild(section);\n }\n\n static render_count(viz: Display, container: HTMLElement) {\n const section = div(\"section\");\n const op_title = div(\"section-title\");\n op_title.innerText = \"Count\";\n section.appendChild(op_title);\n container.appendChild(section);\n\n let opts = EditorPage.string_col_opts(viz);\n\n const none: SelectVal = {\n label: \"None\",\n value: \"\",\n }\n opts.unshift(none);\n\n const selected = viz.count_target ? viz.count_target : \"\";\n const row = EditorPage.select_row(\"Column\", selected, opts);\n section.appendChild(row.container);\n\n row.select.onchange = function () {\n Editor.set_count(viz, row.select.value);\n }\n }\n\n static render_line_style_control(viz: Display, container: HTMLElement) {\n const row = div(\"panel-row\");\n const label = div(\"label\");\n label.innerText = \"Style\";\n const val = div(\"value\");\n\n row.appendChild(label);\n row.appendChild(val);\n container.appendChild(row);\n\n const selector = div(\"selector\", \"selector-full\", \"large-icon-selector\");\n const types = [\"line\", \"step\"];\n for (const t of types) {\n const opt = div(\"option\");\n if (t === \"line\") {\n opt.appendChild(VizSVG.line_style_icon());\n } else {\n opt.appendChild(VizSVG.step_style_icon());\n }\n selector.appendChild(opt);\n if (viz.line_style === t) {\n opt.classList.add(\"selected\");\n }\n opt.onclick = function () {\n const els = selector.querySelectorAll(\"div.option\");\n for (let i = 0; i < els.length; i++) {\n const el = els[i];\n el.classList.remove(\"selected\");\n }\n opt.classList.add(\"selected\");\n viz.line_style = t;\n const attr: ApiAttribute = {\n parent: viz.id,\n key: \"line_style\",\n text: t,\n number: null,\n }\n const update: ApiUpdate = {\n attributes: [attr],\n connections: [],\n }\n App.new_graph_data = true;\n const opts: UpdateOpts = {\n update_thumbnail: true,\n data_changes: false,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n }\n val.appendChild(selector);\n }\n\n static render_curve_control(viz: Display, container: HTMLElement) {\n\n const row = div(\"panel-row\");\n const label = div(\"label\");\n label.innerText = \"Curve\";\n const val = div(\"value\", \"value-flex\", \"slider\");\n const amt = App.input();\n amt.value = viz.line_curve.toString();\n const slide = input();\n slide.type = \"range\";\n slide.value = viz.line_curve.toString();\n val.appendChild(amt);\n val.appendChild(slide);\n\n row.appendChild(label);\n row.appendChild(val);\n container.appendChild(row);\n\n const update = function (n: number, api: boolean) {\n viz.line_curve = n;\n if (api) {\n const attr: ApiAttribute = {\n parent: viz.id,\n key: \"line_curve\",\n text: null,\n number: n,\n }\n const update: ApiUpdate = {\n attributes: [attr],\n connections: [],\n }\n const opts: UpdateOpts = {\n update_thumbnail: true,\n data_changes: false,\n }\n Api.update_display(viz.id, update, opts);\n }\n const g_id = \"viz_\" + viz.id;\n const g = document.querySelector(\"svg #\" + g_id) as SVGGElement;\n Display.render(viz, g, 18);\n }\n\n const apply_amt_value = function () {\n let n = Number(amt.value);\n if (isNaN(n)) {\n return;\n }\n n = Math.max(0, n);\n n = Math.min(100, n);\n slide.value = n.toString();\n update(n, true);\n }\n\n amt.onkeydown = function (e) {\n if (e.keyCode === 13) { // enter\n apply_amt_value();\n }\n };\n\n amt.addEventListener('blur', function () {\n apply_amt_value();\n })\n\n slide.oninput = function () {\n amt.value = slide.value;\n update(Number(slide.value), false);\n }\n\n slide.onchange = function () {\n amt.value = slide.value;\n update(Number(slide.value), true);\n }\n }\n\n static render_graph_settings(viz: Display, container: HTMLElement) {\n const title = div(\"section\", \"section-title\", \"first-section\");\n const selector = div(\"selector\", \"selector-full\", \"icon-selector\");\n const types = [\"bars\", \"lines\", \"number\"];\n for (const t of types) {\n const opt = div(\"option\");\n opt.appendChild(VizSVG.graph_icon(t));\n selector.appendChild(opt);\n if (viz.type === t) {\n opt.classList.add(\"selected\");\n }\n opt.onclick = function () {\n const els = selector.querySelectorAll(\"div.option\");\n for (let i = 0; i < els.length; i++) {\n const el = els[i];\n el.classList.remove(\"selected\");\n }\n opt.classList.add(\"selected\");\n viz.type = t;\n const attr: ApiAttribute = {\n parent: viz.id,\n key: \"type\",\n text: t,\n number: null,\n }\n const update: ApiUpdate = {\n attributes: [attr],\n connections: [],\n }\n App.new_graph_data = true;\n const opts: UpdateOpts = {\n update_thumbnail: true,\n data_changes: false,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n }\n title.appendChild(selector);\n container.appendChild(title);\n\n if (viz.type === \"lines\") {\n const section = div(\"section\");\n const title = div(\"section-title\");\n title.innerText = \"Shape\";\n section.appendChild(title);\n container.appendChild(section);\n\n EditorPage.render_line_style_control(viz, section);\n EditorPage.render_curve_control(viz, section);\n\n }\n }\n\n static render_right_rail(page: Page, viz: Display | null, container: HTMLElement) {\n container.innerHTML = \"\";\n if (!viz) {\n return;\n }\n EditorPage.render_graph_settings(viz, container);\n EditorPage.render_filter(viz, container);\n EditorPage.render_group(viz, container);\n EditorPage.render_sort(viz, container);\n\n // check if count is selected\n if (page.selected_element) {\n const parts = page.selected_element.split(\":\");\n if (parts.length > 1 && parts[1] === \"count\") {\n const col = div(\"section\", \"divider\");\n const col_title = div(\"section-title\");\n col_title.innerText = \"Count\";\n col.appendChild(col_title);\n container.appendChild(col);\n EditorPage.render_count(viz, container);\n return;\n }\n }\n\n const selected_col = Editor.get_selected_column(page);\n if (!selected_col) {\n return;\n }\n\n const col = div(\"section\", \"divider\");\n const col_title = div(\"section-title\");\n col_title.innerText = selected_col.data.column_name;\n col.appendChild(col_title);\n container.appendChild(col);\n\n EditorPage.render_pivot(page, viz, container);\n EditorPage.render_operation(page, viz, container);\n }\n\n private static render_panels(page: Page, container: HTMLElement) {\n const graph_width = 400;\n const inset = 20;\n const width = (graph_width * 2) + (inset * 2);\n const panel = div(\"graph-page\", \"display_00c0f3\");\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.setAttribute(\"viewBox\", \"0 0 \" + width + \" 400\");\n const defs = document.createElementNS(\"http://www.w3.org/2000/svg\", \"defs\");\n const filter = document.createElementNS(\"http://www.w3.org/2000/svg\", \"filter\");\n filter.id = \"shadow\";\n filter.setAttribute(\"x\", \"-20%\");\n filter.setAttribute(\"y\", \"-20%\");\n filter.setAttribute(\"width\", \"140%\");\n filter.setAttribute(\"height\", \"140%\");\n filter.setAttribute(\"filterUnits\", \"objectBoundingBox\");\n filter.setAttribute(\"color-interpolation-filters\", \"linearRGB\");\n\n const shadow = document.createElementNS(\"http://www.w3.org/2000/svg\", \"feDropShadow\");\n shadow.setAttribute(\"dx\", \"0\");\n shadow.setAttribute(\"dy\", \"0\");\n shadow.setAttribute(\"stdDeviation\", \"4\");\n shadow.setAttribute(\"flood-opacity\", \"0.2\");\n filter.appendChild(shadow);\n defs.appendChild(filter);\n svg.appendChild(defs);\n\n panel.appendChild(svg);\n container.appendChild(panel);\n\n let left_height = inset;\n let right_height = inset;\n\n let drag_x = 0;\n let drag_y = 0;\n let moved = false;\n let target_id = \"\";\n\n let node_set: DisplayNode[] = [];\n const spacers: DisplaySpacer[] = [];\n\n const spacer_height = 200;\n const render_spacer = function (group: string, position: number, left_offset: number, top_offset: number): DisplaySpacer {\n const r = SVG.rect(left_offset, top_offset, graph_width, spacer_height);\n r.setAttribute(\"fill\", \"none\");\n svg.appendChild(r);\n const s: DisplaySpacer = {\n group: group,\n position: position,\n element: r,\n }\n spacers.push(s);\n return s;\n }\n const l_spacer = render_spacer(\"left\", 0, inset, left_height);\n const r_spacer = render_spacer(\"right\", 0, (inset + graph_width), right_height);\n\n const y_offset = function (node: DisplayNode) {\n let offset = inset;\n for (const n of node_set) {\n if (n.group !== node.group) {\n continue;\n }\n if (n.position < node.position) {\n offset += n.height;\n }\n }\n return offset;\n }\n\n const reflow = function () {\n for (const n of node_set) {\n if (n.element.id === target_id) {\n continue;\n }\n let x = n.x;\n const y = y_offset(n);\n const transform = \"translate(\" + x + \", \" + y + \")\";\n n.element.setAttribute(\"transform\", transform);\n }\n }\n\n const move_node = function (node: DisplayNode, group: string, pos: number) {\n node.position = pos;\n node.group = group;\n\n let l_idx = 0;\n let r_idx = 0;\n const sorted = node_set.sort(function (a, b) {\n return a.position - b.position;\n });\n for (const n of sorted) {\n if (n.group === \"left\") {\n n.position = l_idx;\n l_idx++;\n } else {\n n.position = r_idx;\n r_idx++;\n }\n }\n node_set = sorted;\n }\n\n const render = function (v: VizConnection, group: string, position: number, left_offset: number, top_offset: number) {\n const g = document.createElementNS(\"http://www.w3.org/2000/svg\", \"g\");\n g.classList.add(\"display\");\n g.id = \"viz_\" + v.viz.id;\n const transform = \"translate(\" + left_offset + \", \" + top_offset + \")\";\n g.setAttribute(\"transform\", transform);\n svg.appendChild(g);\n\n g.onclick = function (e) {\n e.stopPropagation();\n Editor.set_selected_element(v.viz.id);\n App.render();\n }\n const selected_viz = Editor.get_selected_viz(page);\n if (selected_viz && selected_viz.id === v.viz.id) {\n g.classList.add(\"selected\");\n } else {\n g.classList.remove(\"selected\");\n }\n\n const f = App.input();\n const f_x_offset = 18;\n const f_y_offset = 22;\n f.style.left = (left_offset + f_x_offset) + \"px\";\n f.style.top = (top_offset + f_y_offset) + \"px\";\n f.value = v.viz.title;\n panel.appendChild(f);\n\n f.onmousedown = function (e) {\n e.stopPropagation();\n }\n\n f.onclick = function (e) {\n e.stopPropagation();\n }\n\n f.addEventListener('blur', function () {\n App.input_focused = false;\n if (!f.getAttribute(\"cancel\")) {\n const req: ApiDisplayUpdate = {\n title: f.value\n }\n Ajax.post(\"/api/v1/displays/\" + v.viz.id, function () {\n v.viz.title = f.value;\n const v_id = \"viz_\" + v.viz.id;\n const nav_el = document.querySelector(\"div.view-element#\" + v_id + \" span\");\n if (nav_el) {\n nav_el.innerHTML = f.value;\n }\n const title_el = document.querySelector(\"#t_\" + v.viz.id);\n if (title_el) {\n title_el.innerHTML = f.value.toUpperCase();\n }\n }, req, function () {\n f.value = v.viz.title;\n });\n }\n window.setTimeout(function () {\n f.removeAttribute(\"cancel\");\n }, 50);\n })\n\n f.onkeydown = function (e) {\n if (e.code === \"Escape\") {\n f.setAttribute(\"cancel\", \"true\");\n f.blur();\n f.value = v.viz.title;\n } else if (e.code === \"Enter\" || e.code === \"Return\") {\n f.blur();\n }\n }\n\n const size = Display.render(v.viz, g, 18);\n if (left_offset === inset) {\n left_height += size.height;\n } else {\n right_height += size.height;\n }\n\n const node: DisplayNode = {\n viz: v,\n group: group,\n position: position,\n element: g,\n x: left_offset,\n y: top_offset,\n height: size.height,\n }\n\n const drag_move = function (e: MouseEvent) {\n const x_delta = (drag_x - e.clientX) / App.zoom;\n const y_delta = (drag_y - e.clientY) / App.zoom;\n\n if ((Math.abs(x_delta) > 5 || Math.abs(y_delta) > 5) && !moved) {\n target_id = g.id;\n const list = svg.querySelectorAll(\"g.display\");\n if (list.length > 0) {\n list[list.length - 1].after(g);\n }\n moved = true;\n }\n\n const transform = \"translate(\" + (left_offset - x_delta) + \", \" + (top_offset - y_delta) + \")\";\n g.setAttribute(\"transform\", transform);\n panel.classList.add(\"move\");\n\n for (const n of node_set) {\n if (n.element.id === g.id) {\n continue;\n }\n const r = n.element.getBoundingClientRect();\n if (r.left < e.clientX && r.right > e.clientX && r.top < e.clientY && r.bottom > e.clientY) {\n if (e.clientY > (r.top + r.height / 2)) {\n move_node(node, n.group, n.position + 0.5);\n } else {\n move_node(node, n.group, n.position - 0.5);\n }\n }\n }\n for (const s of spacers) {\n const r = s.element.getBoundingClientRect();\n if (r.left < e.clientX && r.right > e.clientX && r.top < e.clientY && r.bottom > e.clientY) {\n move_node(node, s.group, s.position);\n }\n }\n reflow();\n\n e.preventDefault();\n }\n\n const on_drag_move = function (e: MouseEvent) {\n window.requestAnimationFrame(function () {\n drag_move(e);\n });\n }\n\n const drag_end = function () {\n panel.classList.remove(\"move\");\n document.removeEventListener('mousemove', on_drag_move);\n document.removeEventListener('mouseup', drag_end);\n if (!moved) {\n return;\n }\n\n const update: ApiUpdate = {\n attributes: [],\n connections: [],\n }\n for (const n of node_set) {\n n.viz.position = n.position;\n const pos: ApiAttribute = {\n parent: n.viz.id,\n key: \"position\",\n text: null,\n number: n.position,\n }\n const group: ApiAttribute = {\n parent: n.viz.id,\n key: \"group\",\n text: n.group,\n number: null,\n }\n update.attributes.push(pos);\n update.attributes.push(group);\n if (App.selected_page) {\n for (const v of page.viz_list) {\n if (v.id === n.viz.id) {\n v.group = n.group;\n v.position = n.position;\n }\n }\n page.viz_list.sort(function (a, b) {\n return a.position - b.position;\n });\n }\n }\n App.render();\n Api.update_page(page, update, true);\n }\n\n g.onmousedown = function (e) {\n drag_x = e.clientX;\n drag_y = e.clientY;\n moved = false;\n\n document.addEventListener('mousemove', on_drag_move);\n document.addEventListener('mouseup', drag_end);\n e.preventDefault();\n }\n\n node_set.push(node);\n }\n let left_idx = 0;\n let right_idx = 0;\n for (const v of page.viz_list) {\n const x = v.group === \"left\" ? inset : inset + graph_width;\n const y = v.group === \"left\" ? left_height : right_height;\n render(v, v.group, v.position, x, y);\n if (v.group === \"left\") {\n left_idx++;\n } else {\n right_idx++;\n }\n }\n l_spacer.position = left_idx;\n r_spacer.position = right_idx;\n l_spacer.element.setAttribute(\"y\", left_height + \"px\");\n r_spacer.element.setAttribute(\"y\", right_height + \"px\");\n\n const height = Math.max(left_height, right_height) + inset;\n svg.setAttribute(\"viewBox\", \"0 0 \" + width + \" \" + (height + spacer_height) + \"\");\n\n if (App.new_graph_data && App.thumbnail_dirty_count > 0) {\n App.thumbnail_dirty_count--;\n }\n if (App.new_graph_data && App.thumbnail_dirty_count === 0) {\n App.thumbnail_dirty_count--;\n SVG.render_to_image(svg, page.id, Api.upload_thumbnail);\n\n const rect = svg.getBoundingClientRect();\n const ratio = rect.width / rect.height;\n const attr: ApiAttribute = {\n parent: page.id,\n key: \"aspect_ratio\",\n text: null,\n number: ratio,\n }\n const update: ApiUpdate = {\n attributes: [attr],\n connections: [],\n }\n Api.update_page(page, update);\n }\n\n }\n\n static set_transform_origin() {\n const page = document.querySelector(\"div.graph-page\") as HTMLElement;\n const center = document.querySelector(\"div.center\");\n if (page && center) {\n const w = center.getBoundingClientRect().width;\n const h = center.getBoundingClientRect().height;\n const cx = (w / 2) - App.translate_x;\n const cy = (h / 2) - App.translate_y;\n page.style.transformOrigin = cx + \"px \" + cy + \"px\";\n }\n }\n\n static render_main(container: HTMLElement) {\n if (!App.selected_page) {\n return;\n }\n\n let center = container.querySelector(\"div.center\") as HTMLElement;\n if (!center) {\n center = div(\"center\");\n container.appendChild(center);\n center.onclick = function () {\n Editor.set_selected_element(null);\n App.render();\n }\n\n center.onwheel = function (e) {\n e.preventDefault();\n App.translate_x -= (e.deltaX * 0.8) / App.zoom;\n App.translate_y -= (e.deltaY * 0.8) / App.zoom;\n document.body.style.setProperty(\"--translate-x\", App.translate_x + \"\");\n document.body.style.setProperty(\"--translate-y\", App.translate_y + \"\");\n EditorPage.set_transform_origin();\n }\n }\n center.innerHTML = \"\";\n\n EditorPage.render_panels(App.selected_page, center);\n EditorPage.set_transform_origin();\n\n let right = container.querySelector(\"div.right\") as HTMLElement;\n if (!right) {\n right = div(\"right\");\n container.appendChild(right);\n }\n\n const selected_viz = Editor.get_selected_viz(App.selected_page);\n EditorPage.render_right_rail(App.selected_page, selected_viz, right);\n\n let bottom = container.querySelector(\"div.bottom\") as HTMLElement;\n if (!bottom) {\n bottom = div(\"bottom\", \"data\");\n container.appendChild(bottom);\n }\n\n EditorPage.render_data(App.selected_page, selected_viz, bottom);\n if (App.selected_page.data_panel_open) {\n container.classList.add(\"data-open\");\n } else {\n container.classList.remove(\"data-open\");\n }\n }\n\n static update_zoom_ui() {\n const zoom = document.querySelector(\"div.zoom-control\") as HTMLElement;\n if (!zoom) {\n return;\n }\n const label = zoom.querySelector(\"span.zoom-label\") as HTMLElement;\n const plus = zoom.querySelector(\"svg.add-icon\");\n const minus = zoom.querySelector(\"svg.minus-icon\");\n if (!label || !plus || !minus) {\n return;\n }\n\n label.innerText = Math.round(App.zoom * 100) + \"%\";\n if (App.zoom <= 0.25) {\n minus.classList.add(\"disabled\");\n } else {\n minus.classList.remove(\"disabled\");\n }\n if (App.zoom >= 4) {\n plus.classList.add(\"disabled\");\n } else {\n plus.classList.remove(\"disabled\");\n }\n }\n\n static render_nav(nav: HTMLElement) {\n nav.innerHTML = \"\";\n\n if (App.selected_page) {\n const page = App.selected_page;\n const h1 = document.createElement(\"h1\");\n nav.appendChild(h1);\n const f = App.input();\n f.value = page.title;\n h1.appendChild(f);\n\n f.addEventListener('blur', function () {\n App.input_focused = false;\n if (!f.getAttribute(\"cancel\")) {\n const req: ApiPageUpdate = {\n title: f.value\n }\n Ajax.post(\"/api/v1/pages/\" + page.id, function () {\n page.title = f.value;\n }, req, function () {\n f.value = page.title;\n });\n }\n window.setTimeout(function () {\n f.removeAttribute(\"cancel\");\n }, 50);\n })\n\n f.onkeydown = function (e) {\n if (e.code === \"Escape\") {\n f.setAttribute(\"cancel\", \"true\");\n f.blur();\n f.value = page.title;\n } else if (e.code === \"Enter\" || e.code === \"Return\") {\n f.blur();\n }\n }\n }\n\n const spacer = div(\"spacer\");\n nav.appendChild(spacer);\n\n const buttons = div();\n const add_display = VizSVG.display_icon_large();\n buttons.appendChild(add_display);\n nav.appendChild(buttons);\n\n add_display.onclick = function () {\n Editor.add_new_viz();\n }\n\n const divider = div(\"divider\");\n nav.appendChild(divider);\n\n const zoom = div(\"zoom-control\");\n const minus = SVG.minus_icon(26, 10);\n const label_wrap = span(\"zoom-label-wrap\");\n const label = span(\"zoom-label\", \"no-select\");\n label_wrap.appendChild(label);\n label.innerText = \"100%\";\n const plus = SVG.plus_icon(26, 10);\n zoom.appendChild(minus);\n zoom.appendChild(label_wrap);\n zoom.appendChild(plus);\n nav.appendChild(zoom);\n\n minus.onclick = function () {\n Editor.zoom_out();\n }\n\n plus.onclick = function () {\n Editor.zoom_in();\n }\n\n const menu = Menu.menu();\n Menu.add_menu_item(menu, \"Zoom In\", function () {\n Editor.zoom_in();\n }, \"+\");\n Menu.add_menu_item(menu, \"Zoom Out\", function () {\n Editor.zoom_out();\n }, \"-\");\n Menu.add_menu_item(menu, \"Zoom to Fit\", function () {\n Editor.zoom_to_fit();\n }, \"1\");\n Menu.add_menu_item(menu, \"Zoom to 100%\", function () {\n Editor.zoom_reset();\n }, \"0\");\n label_wrap.appendChild(menu.container);\n\n nav.appendChild(div(\"spacer\"));\n\n const button = div(\"button\", \"run-button\");\n if (App.updating_count > 0) {\n button.classList.add(\"working\");\n }\n button.innerText = \"Run\";\n const loading = Loading.overlay();\n button.appendChild(loading);\n nav.appendChild(button);\n button.onclick = function () {\n Editor.run();\n }\n\n const view_button = anchor(\"button\", \"light\", \"icon\");\n view_button.appendChild(VizSVG.open_icon());\n nav.appendChild(view_button);\n view_button.href = \"/page/\" + App.selected_page?.id;\n view_button.onclick = function (e) {\n if (e.button === 0 && !e.ctrlKey && !e.metaKey) {\n e.preventDefault();\n window.open(view_button.href, \"_blank\");\n }\n }\n\n EditorPage.update_zoom_ui();\n }\n\n}", "import { Ajax } from \"../../shared/ajax\";\nimport { ApiBQCol, ApiBQResponse, ApiAttribute, ApiUpdate, ApiConnection, ApiVizCreateRequest, ApiDisplay, ApiErrorResponse, ApiBQQuery } from \"./api_data\";\nimport { App, BQData, PivotMeasure } from \"./app\";\nimport { BQ } from \"./bq\";\nimport * as CodeMirror from 'codemirror';\nimport 'codemirror/mode/sql/sql.js';\nimport { Api, UpdateOpts } from \"./api\";\nimport { Display, DataConnection, TableConnection, FilterConnection } from \"./display\";\nimport { EditorPage } from \"./editor_page\";\nimport uuid = require(\"uuid\");\nimport { Page, VizConnection } from \"./page\";\nimport { Overlay } from \"../../shared/overlay\";\nimport { Menu } from \"../../shared/menu\";\n\nexport enum ColumnFilter {\n NoFilter,\n NumericOnly,\n}\n\nexport interface ColumnSelectionData {\n attributes: ApiAttribute[],\n connections: ApiConnection[],\n connection_id: string;\n col_data: BQData,\n}\n\nexport interface SelectVal {\n label: string;\n value: string;\n}\n\nexport class Editor {\n\n static date_groups: SelectVal[] = [\n {\n label: \"Day\",\n value: \"Day\",\n },\n {\n label: \"Week\",\n value: \"ISOWeek\",\n },\n {\n label: \"Month\",\n value: \"Month\",\n },\n {\n label: \"Quarter\",\n value: \"Quarter\",\n },\n {\n label: \"Year\",\n value: \"Year\",\n }\n ]\n static date_groups_plural: SelectVal[] = [\n {\n label: \"Hours\",\n value: \"Hour\",\n },\n {\n label: \"Days\",\n value: \"Day\",\n },\n {\n label: \"Weeks\",\n value: \"ISOWeek\",\n },\n {\n label: \"Months\",\n value: \"Month\",\n },\n {\n label: \"Quarters\",\n value: \"Quarter\",\n },\n {\n label: \"Years\",\n value: \"Year\",\n }\n ]\n static date_recent: SelectVal = {\n label: \"In the past...\",\n value: \"Recent\",\n }\n static date_current: SelectVal = {\n label: \"In the current...\",\n value: \"Current\",\n }\n static date_custom: SelectVal = {\n label: \"Custom\",\n value: \"Custom\",\n }\n static text_match: SelectVal = {\n label: \"Is equal to\",\n value: \"Match\",\n }\n static text_not_match: SelectVal = {\n label: \"Is not equal to\",\n value: \"NotMatch\",\n }\n static date_pivots = [\"Day Of Week\", \"Month Of Year\", \"Quarter Of Year\"];\n static date_pivot_values: { [id: string]: string[] } = {\n \"Day Of Week\": [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\"],\n //\"Day Of Month\": [],\n \"Month Of Year\": [\"January\", \"February\", \"March\", \"April\", \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \"November\", \"December\"],\n \"Quarter Of Year\": [\"Q1\", \"Q2\", \"Q3\", \"Q4\"]\n };\n static operations: SelectVal[] = [\n {\n label: \"Sum\",\n value: \"Sum\",\n },\n {\n label: \"Avg\",\n value: \"Avg\",\n },\n {\n label: \"Min\",\n value: \"Min\",\n },\n {\n label: \"Max\",\n value: \"Max\",\n },\n ];\n static sort_orders: SelectVal[] = [\n {\n label: \"Asc\",\n value: \"Asc\",\n },\n {\n label: \"Desc\",\n value: \"Desc\",\n }\n ];\n static editor: CodeMirror.Editor | null = null;\n\n static column_key(dataset_id: string, table_id: string, column_name: string, pivot: string | null): string {\n const p = pivot ? \".\" + pivot : \"\";\n return dataset_id + \".\" + table_id + \".\" + column_name + p;\n }\n\n static data_key(data: BQData, include_pivot: boolean): string {\n const p = include_pivot ? data.pivot : null;\n return Editor.column_key(data.dataset_id, data.table_id, data.column_name, p);\n }\n\n static get_selected_column(page: Page): DataConnection | null {\n const viz_list: Display[] = [];\n for (const conn of page.viz_list) {\n viz_list.push(conn.viz);\n }\n for (const viz of viz_list) {\n for (const col of viz.selected_columns) {\n const id = viz.selected_table?.id + \":\" + col.id;\n if (id === page.selected_element) {\n return col;\n }\n }\n }\n return null;\n }\n\n static get_selected_viz(page: Page): Display | null {\n const viz_list: Display[] = [];\n for (const conn of page.viz_list) {\n viz_list.push(conn.viz);\n }\n for (const viz of viz_list) {\n const count_id = viz.selected_table?.id + \":count\";\n if (page.selected_element === count_id) {\n return viz;\n }\n if (viz.id === page.selected_element || viz.selected_table && viz.selected_table.id === page.selected_element) {\n return viz;\n }\n for (const col of viz.selected_columns) {\n const id = viz.selected_table?.id + \":\" + col.id;\n if (id === page.selected_element) {\n return viz;\n }\n }\n }\n return null;\n }\n\n static set_selected_element(element: string | null) {\n if (!App.user) {\n return;\n }\n if (!App.selected_page) {\n return;\n }\n const attr: ApiAttribute = {\n parent: App.user.id,\n key: \"selected_element\",\n text: element,\n number: null,\n }\n const update: ApiUpdate = {\n attributes: [attr],\n connections: [],\n }\n App.selected_page.selected_element = element;\n Api.update_page(App.selected_page, update);\n }\n\n static set_data_panel_open(page: Page, open: boolean) {\n if (!App.user) {\n return;\n }\n const b = open ? 1 : 0;\n const attr: ApiAttribute = {\n parent: App.user.id,\n key: \"data_panel_open\",\n text: null,\n number: b,\n }\n const update: ApiUpdate = {\n attributes: [attr],\n connections: [],\n }\n page.data_panel_open = open;\n Api.update_page(page, update);\n }\n\n static column_selection_data(viz_id: string, table_connection: TableConnection, col: ApiBQCol, position: number): ColumnSelectionData {\n let group_by: string | null = null;\n if (BQ.date_col(col.type)) {\n group_by = \"Day\";\n }\n\n const sel: BQData = {\n project_id: table_connection.table.project_id,\n dataset_id: table_connection.table.dataset_id,\n table_id: table_connection.table.id,\n column_name: col.name,\n column_type: col.type,\n rows: [],\n pivoted: false,\n pivot_facet: null,\n pivot: null,\n pivot_op: null,\n pivot_target: null,\n pivot_measures: [],\n operation: null,\n loading: false,\n hidden: false,\n closed: false,\n }\n\n const conn: ApiConnection = {\n id: uuid(),\n parent: viz_id,\n key: \"column\",\n child: col.name,\n deleted: false,\n }\n const pos: ApiAttribute = {\n parent: conn.id,\n key: \"position\",\n text: null,\n number: position,\n }\n const attrs: ApiAttribute[] = [pos];\n const conns: ApiConnection[] = [conn];\n\n if (group_by) {\n const group_attr: ApiAttribute = {\n parent: conn.id,\n key: \"group_by\",\n text: group_by,\n number: null,\n }\n attrs.push(group_attr);\n }\n\n return {\n attributes: attrs,\n connections: conns,\n connection_id: conn.id,\n col_data: sel,\n }\n }\n\n static add_column(viz: Display, col: ApiBQCol) {\n if (viz.selected_table == null) {\n return;\n }\n\n const data = Editor.column_selection_data(viz.id, viz.selected_table, col, viz.selected_columns.length);\n\n const update: ApiUpdate = {\n attributes: data.attributes,\n connections: data.connections,\n }\n if (App.user) {\n const selection_attr: ApiAttribute = {\n parent: App.user.id,\n key: \"selected_element\",\n text: data.connection_id,\n number: null,\n }\n update.attributes.push(selection_attr);\n }\n Api.update_display(viz.id, update);\n\n const c: DataConnection = {\n viz_id: viz.id,\n id: data.connection_id,\n data: data.col_data,\n position: viz.selected_columns.length,\n }\n viz.selected_columns.push(c);\n // TODO: move to page\n //viz.selected_element = data.connection_id;\n App.render();\n }\n\n static remove_column(page: Page) {\n const selected_col = Editor.get_selected_column(page);\n if (App.input_focused || !selected_col || selected_col.data.pivot) {\n return;\n }\n const viz_list: Display[] = [];\n for (const conn of page.viz_list) {\n viz_list.push(conn.viz);\n }\n const filtered = [];\n const key = Editor.data_key(selected_col.data, false);\n const api_key = Editor.data_key(selected_col.data, true);\n const update: ApiUpdate = {\n attributes: [],\n connections: [],\n }\n for (const viz of viz_list) {\n let matching_viz = false;\n for (const s of viz.selected_columns) {\n const s_key = Editor.data_key(s.data, false);\n const s_api_key = Editor.data_key(s.data, true);\n if (s_key === key && s_api_key === api_key) {\n matching_viz = true;\n const conn: ApiConnection = {\n id: selected_col.id,\n parent: viz.id,\n key: \"column\",\n child: s.data.column_name,\n deleted: true,\n }\n update.connections.push(conn);\n } else {\n filtered.push(s);\n }\n }\n if (matching_viz) {\n viz.selected_columns = filtered;\n Api.update_display(viz.id, update);\n break;\n }\n }\n if (App.user) {\n const sel_attr: ApiAttribute = {\n parent: App.user?.id,\n key: \"selected_element\",\n text: null,\n number: null,\n }\n update.attributes.push(sel_attr);\n }\n App.render();\n\n }\n\n static remove_filter(display: Display, filter: FilterConnection) {\n const api_conn: ApiConnection = {\n id: filter.id,\n parent: display.id,\n key: \"filter\",\n child: filter.column,\n deleted: true,\n }\n const filtered: FilterConnection[] = [];\n for (const f of display.filters) {\n if (f.id !== filter.id) {\n filtered.push(f);\n }\n }\n display.filters = filtered;\n const update: ApiUpdate = {\n attributes: [],\n connections: [api_conn],\n }\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(display.id, update, opts);\n App.render();\n }\n\n static filter_attributes(filter: FilterConnection): ApiAttribute[] {\n return [\n {\n parent: filter.id,\n key: \"column\",\n text: filter.column,\n number: null,\n },\n {\n parent: filter.id,\n key: \"date_mode\",\n text: filter.date_mode,\n number: null,\n },\n {\n parent: filter.id,\n key: \"date_current_interval\",\n text: filter.date_current_interval,\n number: null,\n },\n {\n parent: filter.id,\n key: \"date_recent_interval\",\n text: filter.date_recent_interval,\n number: null,\n },\n {\n parent: filter.id,\n key: \"date_recent_count\",\n text: null,\n number: filter.date_recent_count,\n },\n {\n parent: filter.id,\n key: \"date_min\",\n text: filter.date_min,\n number: null,\n },\n {\n parent: filter.id,\n key: \"date_max\",\n text: filter.date_max,\n number: null,\n },\n {\n parent: filter.id,\n key: \"text_mode\",\n text: filter.text_mode,\n number: null,\n },\n {\n parent: filter.id,\n key: \"text_query\",\n text: filter.text_query,\n number: null,\n }\n ]\n }\n\n static add_filter(display: Display, column: string) {\n const filter: FilterConnection = {\n id: uuid(),\n viz_id: display.id,\n column: column,\n date_mode: Editor.date_recent.value,\n date_current_interval: Editor.date_groups[2].value,\n date_recent_interval: Editor.date_groups[0].value,\n date_recent_count: 30,\n date_min: null,\n date_max: null,\n text_mode: Editor.text_match.value,\n text_query: null,\n }\n display.filters.push(filter);\n const api_conn: ApiConnection = {\n id: filter.id,\n parent: display.id,\n key: \"filter\",\n child: column,\n deleted: false,\n }\n const update: ApiUpdate = {\n attributes: Editor.filter_attributes(filter),\n connections: [api_conn],\n }\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(display.id, update, opts);\n App.render();\n }\n\n static update_filter(display: Display, filter: FilterConnection) {\n const update: ApiUpdate = {\n attributes: Editor.filter_attributes(filter),\n connections: [],\n }\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(display.id, update, opts);\n App.render();\n }\n\n static set_group_by(viz: Display, column: string | null, interval: string | null) {\n viz.group_by = column;\n viz.group_by_interval = interval;\n const a: ApiAttribute = {\n parent: viz.id,\n key: \"group_by\",\n text: column,\n number: null,\n };\n const int: ApiAttribute = {\n parent: viz.id,\n key: \"group_by_interval\",\n text: interval,\n number: null,\n };\n const update: ApiUpdate = {\n attributes: [a, int],\n connections: [],\n }\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static set_sort(viz: Display, column: string | null, order: string | null) {\n viz.sort = column;\n viz.sort_order = order;\n const a: ApiAttribute = {\n parent: viz.id,\n key: \"sort\",\n text: column,\n number: null,\n };\n const int: ApiAttribute = {\n parent: viz.id,\n key: \"sort_order\",\n text: order,\n number: null,\n };\n const update: ApiUpdate = {\n attributes: [a, int],\n connections: [],\n }\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static set_count(viz: Display, column: string | null) {\n // convert empty string to null\n const c = column === \"\" ? null : column;\n viz.count_target = c;\n const a: ApiAttribute = {\n parent: viz.id,\n key: \"count\",\n text: column,\n number: null,\n };\n const update: ApiUpdate = {\n attributes: [a],\n connections: [],\n }\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static set_operation(viz: Display, conn: DataConnection, op: string | null) {\n conn.data.operation = op;\n const a: ApiAttribute = {\n parent: conn.id,\n key: \"operation\",\n text: op,\n number: null,\n };\n const update: ApiUpdate = {\n attributes: [a],\n connections: [],\n }\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static add_pivot_values(display: Display, conn: DataConnection, values: string[], pivot_facet: string | null): ApiUpdate {\n const update: ApiUpdate = {\n connections: [],\n attributes: [],\n };\n\n if (!display.selected_table) {\n return update;\n }\n\n for (let i = 0; i < values.length; i++) {\n const val = values[i];\n const api_conn: ApiConnection = {\n id: uuid(),\n parent: conn.id,\n key: \"pivot_value\",\n child: val,\n deleted: false,\n }\n update.connections.push(api_conn);\n const pos: ApiAttribute = {\n parent: api_conn.id,\n key: \"position\",\n text: null,\n number: Number(conn.position + \".\" + String(i)),\n }\n update.attributes.push(pos);\n const p_sel: BQData = {\n project_id: display.selected_table.table.project_id,\n dataset_id: display.selected_table.table.dataset_id,\n table_id: display.selected_table.table.id,\n column_name: conn.data.column_name,\n column_type: conn.data.column_type,\n rows: [],\n pivoted: false,\n pivot_facet: pivot_facet,\n pivot: val,\n pivot_op: null,\n pivot_target: null,\n pivot_measures: [],\n operation: null,\n loading: false,\n hidden: false,\n closed: false,\n }\n let idx = 0;\n for (const c of display.selected_columns) {\n if (c.data.column_name === conn.data.column_name) {\n break;\n }\n idx++;\n }\n const p_conn: DataConnection = {\n viz_id: display.id,\n id: api_conn.id,\n data: p_sel,\n position: idx + 1 + i,\n }\n display.selected_columns.splice(idx + 1 + i, 0, p_conn);\n }\n return update;\n }\n\n static add_string_pivot(display: Display, conn: DataConnection) {\n const table_path = conn.data.dataset_id + \".\" + conn.data.table_id;\n const q: ApiBQQuery = {\n project_id: conn.data.project_id,\n dataset_id: conn.data.dataset_id,\n table_id: conn.data.table_id,\n query: \"SELECT DISTINCT(\" + conn.data.column_name + \") as \" + conn.data.column_name + \" FROM \" + table_path + \" ORDER BY \" + conn.data.column_name + \" ASC LIMIT 100;\"\n }\n Ajax.post(\"/api/v1/bq_query\", function (data: ApiBQResponse) {\n conn.data.loading = false;\n conn.data.pivoted = true;\n const values: string[] = [];\n for (let i = 0; i < data.rows.length; i++) {\n if (data.rows[i].length > 0) {\n values.push(data.rows[i][0]);\n }\n }\n const update = Editor.add_pivot_values(display, conn, values, null);\n const piv: ApiAttribute = {\n parent: conn.id,\n key: \"pivoted\",\n text: null,\n number: 1,\n }\n update.attributes.push(piv);\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(conn.viz_id, update, opts);\n App.render();\n }, q);\n }\n\n static add_date_pivot(display: Display, conn: DataConnection) {\n const key = Editor.date_pivots[0];\n conn.data.pivoted = true;\n conn.data.pivot_facet = key;\n const values = Editor.date_pivot_values[key];\n const update = Editor.add_pivot_values(display, conn, values, key);\n const piv: ApiAttribute = {\n parent: conn.id,\n key: \"pivoted\",\n text: null,\n number: 1,\n }\n const facet: ApiAttribute = {\n parent: conn.id,\n key: \"pivot_facet\",\n text: key,\n number: null,\n }\n update.attributes.push(piv);\n update.attributes.push(facet);\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(conn.viz_id, update, opts);\n App.render();\n }\n\n static add_pivot(display: Display, conn: DataConnection) {\n if (conn.data.column_type === \"STRING\") {\n Editor.add_string_pivot(display, conn);\n } else if (BQ.date_col(conn.data.column_type)) {\n Editor.add_date_pivot(display, conn);\n }\n }\n\n static remove_pivot(conn: DataConnection) {\n if (!App.selected_page) {\n return;\n }\n let viz: Display | null = null;\n for (const v of App.selected_page.viz_list) {\n if (v.id === conn.viz_id) {\n viz = v.viz;\n break;\n }\n }\n if (!viz) {\n return;\n }\n\n const attr: ApiAttribute = {\n parent: conn.id,\n key: \"pivoted\",\n text: null,\n number: null,\n }\n const update: ApiUpdate = {\n connections: [],\n attributes: [attr],\n };\n conn.data.pivoted = false;\n const filtered: DataConnection[] = [];\n const key = Editor.data_key(conn.data, false);\n for (const c of viz.selected_columns) {\n const k = Editor.data_key(c.data, false);\n if (k === key && c.data.pivot) {\n const api_conn: ApiConnection = {\n id: c.id,\n parent: conn.id,\n key: \"pivot_value\",\n child: c.data.pivot,\n deleted: true,\n }\n update.connections.push(api_conn);\n } else {\n filtered.push(c);\n }\n }\n viz.selected_columns = filtered;\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static set_pivot_op(display: Display, conn: DataConnection, op: string | null) {\n conn.data.pivot_op = op;\n const key = Editor.data_key(conn.data, false);\n for (const c of display.selected_columns) {\n const k = Editor.data_key(c.data, false);\n if (k === key) {\n c.data.pivot_op = op;\n }\n }\n const op_attr: ApiAttribute = {\n parent: conn.id,\n key: \"pivot_operation\",\n text: op,\n number: null,\n }\n const update: ApiUpdate = {\n connections: [],\n attributes: [op_attr],\n };\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(display.id, update, opts);\n App.render();\n }\n\n static add_pivot_measure(display: Display, conn: DataConnection) {\n if (!display.selected_table) {\n return;\n }\n let measure_col = \"\";\n if (display.selected_table.table.columns) {\n for (const c of display.selected_table.table.columns) {\n if (BQ.numeric_col(c.type)) {\n let existing = false;\n for (const m of conn.data.pivot_measures) {\n if (m.column === c.name) {\n existing = true;\n break;\n }\n }\n if (!existing) {\n measure_col = c.name;\n break;\n }\n }\n }\n }\n if (measure_col === \"\") {\n return;\n }\n const measure: PivotMeasure = {\n id: uuid(),\n column: measure_col,\n }\n conn.data.pivot_measures.push(measure);\n const api_conn: ApiConnection = {\n id: measure.id,\n parent: conn.id,\n key: \"pivot_measure\",\n child: measure.column,\n deleted: false,\n }\n const update: ApiUpdate = {\n connections: [api_conn],\n attributes: [],\n };\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(display.id, update, opts);\n App.render();\n }\n\n static remove_pivot_measure(viz: Display, conn: DataConnection, measure: PivotMeasure) {\n const filtered: PivotMeasure[] = [];\n for (const m of conn.data.pivot_measures) {\n if (m !== measure) {\n filtered.push(m);\n }\n }\n conn.data.pivot_measures = filtered;\n const api_conn: ApiConnection = {\n id: measure.id,\n parent: conn.id,\n key: \"pivot_measure\",\n child: measure.column,\n deleted: true,\n }\n const update: ApiUpdate = {\n connections: [api_conn],\n attributes: [],\n };\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static update_pivot_measure(viz: Display, conn: DataConnection, measure: PivotMeasure, new_column: string) {\n measure.column = new_column;\n const api_conn: ApiConnection = {\n id: measure.id,\n parent: conn.id,\n key: \"pivot_measure\",\n child: measure.column,\n deleted: false,\n }\n const update: ApiUpdate = {\n connections: [api_conn],\n attributes: [],\n };\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static delete_selected_viz() {\n if (Editor.editor && Editor.editor.hasFocus()) {\n return;\n }\n if (Overlay.overlays.length > 0 || Menu.menu_open || App.input_focused || !App.selected_page) {\n return;\n }\n const selected_viz = Editor.get_selected_viz(App.selected_page);\n if (!selected_viz || selected_viz.id !== App.selected_page.selected_element) {\n return;\n }\n const page = App.selected_page;\n let conn: VizConnection | null = null;\n for (const v of page.viz_list) {\n if (v.viz.id === selected_viz.id) {\n conn = v;\n break;\n }\n }\n if (!conn) {\n return;\n }\n\n const conn_update: ApiConnection = {\n id: conn.id,\n parent: page.id,\n key: \"viz\",\n child: conn.viz.id,\n deleted: true,\n }\n const update: ApiUpdate = {\n attributes: [],\n connections: [conn_update],\n }\n const update_thumbnail = true;\n Api.update_page(page, update, update_thumbnail);\n const filtered = [];\n for (const v of page.viz_list) {\n if (v.id !== conn.id) {\n filtered.push(v);\n }\n }\n page.viz_list = filtered;\n App.render();\n }\n\n static set_visibility(viz: Display, conn: DataConnection, hidden: boolean) {\n conn.data.hidden = hidden;\n const h = hidden ? 1 : 0;\n const attr: ApiAttribute = {\n parent: conn.id,\n key: \"hidden\",\n text: null,\n number: h,\n }\n const update: ApiUpdate = {\n connections: [],\n attributes: [attr],\n };\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static set_count_visibility(viz: Display, hidden: boolean) {\n viz.count.hidden = hidden;\n const h = hidden ? 1 : 0;\n const attr: ApiAttribute = {\n parent: viz.id,\n key: \"count_hidden\",\n text: null,\n number: h,\n }\n const update: ApiUpdate = {\n connections: [],\n attributes: [attr],\n };\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static set_pivot_closed(viz: Display, conn: DataConnection, closed: boolean) {\n conn.data.closed = closed;\n const c = closed ? 1 : 0;\n const attr: ApiAttribute = {\n parent: conn.id,\n key: \"closed\",\n text: null,\n number: c,\n }\n const update: ApiUpdate = {\n connections: [],\n attributes: [attr],\n };\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: false,\n }\n Api.update_display(viz.id, update, opts);\n }\n\n static set_pivot_sub_values_visibility(viz: Display, conn: DataConnection, hidden: boolean) {\n const update: ApiUpdate = {\n connections: [],\n attributes: [],\n };\n const key = Editor.data_key(conn.data, false);\n for (const s of viz.selected_columns) {\n const k = Editor.data_key(s.data, false);\n if (k === key && s.data.pivot) {\n s.data.hidden = hidden;\n const h = hidden ? 1 : 0;\n const attr: ApiAttribute = {\n parent: s.id,\n key: \"hidden\",\n text: null,\n number: h,\n }\n update.attributes.push(attr);\n }\n }\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: true,\n }\n Api.update_display(viz.id, update, opts);\n App.render();\n }\n\n static set_viz_closed(viz: Display, closed: boolean) {\n viz.closed = closed;\n const c = closed ? 1 : 0;\n const attr: ApiAttribute = {\n parent: viz.id,\n key: \"closed\",\n text: null,\n number: c,\n }\n const update: ApiUpdate = {\n connections: [],\n attributes: [attr],\n };\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: false,\n }\n Api.update_display(viz.id, update, opts);\n }\n\n static set_table_closed(viz: Display, closed: boolean) {\n if (!viz.selected_table) {\n return;\n }\n viz.selected_table.closed = closed;\n const c = closed ? 1 : 0;\n const attr: ApiAttribute = {\n parent: viz.selected_table.id,\n key: \"closed\",\n text: null,\n number: c,\n }\n const update: ApiUpdate = {\n connections: [],\n attributes: [attr],\n };\n const opts: UpdateOpts = {\n update_thumbnail: false,\n data_changes: false,\n }\n Api.update_display(viz.id, update, opts);\n }\n\n static add_new_viz() {\n if (!App.selected_page) {\n return;\n }\n const page = App.selected_page;\n\n // new viz\n const viz_id = uuid();\n const req: ApiVizCreateRequest = {\n id: viz_id,\n owner_id: App.selected_owner_id,\n }\n\n let list = page.viz_list;\n let group_key = \"left\";\n let left_height = 0;\n let right_height = 0;\n for (const v of page.viz_list) {\n const g_id = \"viz_\" + v.viz.id;\n const g = document.querySelector(\"svg #\" + g_id) as SVGGElement;\n if (g) {\n if (v.group === \"left\") {\n left_height += g.getBoundingClientRect().height;\n } else {\n right_height += g.getBoundingClientRect().height;\n }\n }\n }\n if (left_height > right_height) {\n group_key = \"right\";\n }\n\n const conn: ApiConnection = {\n id: uuid(),\n parent: page.id,\n key: \"viz\",\n child: viz_id,\n deleted: false,\n }\n\n const group: ApiAttribute = {\n parent: conn.id,\n key: \"group\",\n text: group_key,\n number: null,\n }\n const pos: ApiAttribute = {\n parent: conn.id,\n key: \"position\",\n text: null,\n number: list.length,\n }\n const update: ApiUpdate = {\n attributes: [group, pos],\n connections: [conn],\n }\n\n Ajax.post(\"/api/v1/displays\", function (data: ApiDisplay) {\n const viz = Display.parse(data, App.tables);\n const vc: VizConnection = {\n id: conn.id,\n viz: viz,\n position: list.length,\n group: group_key,\n }\n list.push(vc);\n const update_thumbnail = true;\n Api.update_page(page, update, update_thumbnail);\n Editor.set_selected_element(viz_id);\n App.render();\n }, req);\n }\n\n static zoom_in() {\n if (App.zoom >= 4) {\n return;\n }\n if (App.zoom < 0.5) {\n App.zoom = 0.5;\n } else if (App.zoom < 1) {\n App.zoom = 1;\n } else if (App.zoom < 2) {\n App.zoom = 2;\n } else if (App.zoom < 4) {\n App.zoom = 4;\n }\n\n document.body.style.setProperty(\"--zoom\", App.zoom + \"\");\n EditorPage.update_zoom_ui();\n }\n\n static zoom_out() {\n if (App.zoom <= .25) {\n return;\n }\n if (App.zoom > 2) {\n App.zoom = 2;\n } else if (App.zoom > 1) {\n App.zoom = 1;\n } else if (App.zoom > 0.5) {\n App.zoom = 0.5;\n } else if (App.zoom > 0.25) {\n App.zoom = 0.25;\n }\n\n document.body.style.setProperty(\"--zoom\", App.zoom + \"\");\n EditorPage.update_zoom_ui();\n }\n\n static zoom_to_fit() {\n const page = document.querySelector(\"div.graph-page\");\n const center = document.querySelector(\"div.center\");\n if (!page || !center) {\n return;\n }\n\n const padding = 15;\n const page_w = page.getBoundingClientRect().width / App.zoom;\n const page_h = page.getBoundingClientRect().height / App.zoom;\n const center_w = center.getBoundingClientRect().width - (padding * 2);\n const center_h = center.getBoundingClientRect().height - padding * 2;\n const w = center_w / page_w;\n const h = center_h / page_h;\n let z = Math.min(w, h);\n if (z > 1) {\n z = 1;\n }\n App.zoom = z;\n\n let x_off = 0;\n if (center_w < page_w) {\n x_off = padding + (center_w / 2) - (page_w / 2);\n }\n const y_off = padding + (center_h / 2) - (page_h / 2);\n\n App.translate_x = x_off;\n App.translate_y = y_off;\n document.body.style.setProperty(\"--translate-x\", App.translate_x + \"\");\n document.body.style.setProperty(\"--translate-y\", App.translate_y + \"\");\n document.body.style.setProperty(\"--zoom\", App.zoom + \"\");\n EditorPage.update_zoom_ui();\n EditorPage.set_transform_origin();\n }\n\n static zoom_reset() {\n App.zoom = 1;\n document.body.style.setProperty(\"--zoom\", App.zoom + \"\");\n EditorPage.update_zoom_ui();\n }\n\n static run(viz?: Display) {\n\n const run_viz = function (viz: Display) {\n App.updating_count++;\n const bottom = document.querySelector(\"div.bottom\") as HTMLElement;\n const loading = document.querySelector(\"div.bottom div.loading-overlay\") as HTMLElement;\n if (loading) {\n loading.style.display = \"flex\";\n }\n const button = document.querySelector(\"div.run-button\") as HTMLElement;\n if (button) {\n button.classList.add(\"working\");\n }\n App.thumbnail_dirty_count++;\n\n const on_complete = function () {\n App.updating_count--;\n if (!App.selected_page) {\n return;\n }\n EditorPage.render_data(App.selected_page, viz, bottom);\n const editor = document.querySelector(\"div.editor\") as HTMLElement;\n EditorPage.render_main(editor);\n if (App.updating_count > 0) {\n return;\n }\n if (loading) {\n loading.style.display = \"none\";\n }\n // re-select element, in case page has been rendered again\n const button = document.querySelector(\"div.run-button\") as HTMLElement;\n if (button) {\n button.classList.remove(\"working\");\n }\n }\n if (!viz.selected_table) {\n return;\n }\n\n BQ.run(viz.selected_table.table, viz, function () {\n App.new_graph_data = true;\n on_complete();\n }, function (_data: ApiErrorResponse) {\n on_complete();\n });\n }\n\n if (viz !== undefined) {\n run_viz(viz);\n } else if (App.selected_page) {\n for (const v of App.selected_page.viz_list) {\n run_viz(v.viz);\n }\n }\n }\n}\n", "import { div } from './dom';\n\nexport enum DropdownOptionType {\n Selection,\n Divider,\n}\n\ninterface SelectedFunc {\n (selected_option: DropdownOption): boolean;\n}\n\ninterface DropdownCallBack {\n (dropdown_option: DropdownOption): void;\n}\n\nexport class DropdownState {\n\n static menu_focused: boolean = false;\n static key_nav_in_progress: boolean = false;\n static key_nav_timer: number = 0;\n\n static setMenuFocused(value: boolean) {\n // delay clearing menu focus, to prevent a single click registering\n // as both a focus clear and a non-menu_focused click\n if (value === false) {\n setTimeout(function () {\n DropdownState.menu_focused = value;\n }, 200);\n } else {\n DropdownState.menu_focused = value;\n }\n }\n\n static setKeyNavigation(value: boolean) {\n if (value === false) {\n DropdownState.key_nav_timer = window.setTimeout(function () {\n DropdownState.key_nav_in_progress = false;\n }, 200);\n } else {\n clearTimeout(DropdownState.key_nav_timer);\n DropdownState.key_nav_in_progress = true;\n }\n }\n}\n\nexport class DropdownOption {\n label: string = \"\";\n value: T;\n type: DropdownOptionType = DropdownOptionType.Selection;\n keyboard_shortcut: string | null = null;\n selected: boolean = false;\n href?: string;\n\n constructor(label: string, value: T, type?: DropdownOptionType, keyboard_shortcut?: string, href?: string) {\n this.label = label;\n this.value = value;\n if (type) {\n this.type = type;\n }\n if (keyboard_shortcut) {\n this.keyboard_shortcut = keyboard_shortcut;\n }\n if (href !== undefined) {\n this.href = href;\n }\n }\n}\n\nexport function viewSelector(label_string: string, selected_option: string, options: DropdownOption[], cb: DropdownCallBack): HTMLDivElement {\n const d = div(\"view-attribute\");\n const label = div(\"view-attribute-label\");\n label.innerHTML = label_string;\n const dropdown = viewDropdown(selected_option, options, cb);\n d.appendChild(label);\n d.appendChild(dropdown);\n return d;\n}\n\nfunction viewDropdownInputElement(selected_option: string): HTMLInputElement {\n const input = document.createElement(\"input\");\n input.classList.add(\"dropdown-value\", \"noselect\");\n input.setAttribute(\"readonly\", \"true\");\n input.value = selected_option;\n input.innerHTML = selected_option;\n return input;\n}\n\nfunction viewDropdownOption(options_el: HTMLElement, option: DropdownOption, cb: DropdownCallBack): HTMLElement {\n const a = document.createElement(\"a\");\n if (option.selected) {\n a.classList.add(\"selected\");\n }\n\n if (option.href !== undefined) {\n a.classList.add(\"link\");\n }\n\n a.innerHTML = option.label;\n\n if (option.keyboard_shortcut) {\n const k = document.createElement(\"span\");\n k.innerHTML = option.keyboard_shortcut;\n a.appendChild(k);\n }\n\n a.onmouseenter = function () {\n if (DropdownState.key_nav_in_progress) {\n return;\n }\n for (let i = 0; i < options_el.childNodes.length; i++) {\n const child = options_el.childNodes[i] as HTMLElement;\n if (child.classList.contains(\"hover\")) {\n child.classList.remove(\"hover\");\n break;\n }\n }\n a.classList.add(\"hover\");\n };\n a.onmouseleave = function () {\n if (DropdownState.key_nav_in_progress) {\n return;\n }\n a.classList.remove(\"hover\");\n };\n\n a.onmousedown = function (e) {\n e.preventDefault();\n e.stopPropagation();\n cb(option);\n };\n\n return a;\n}\n\nexport function viewDropdownOptions(selected_option: string, options: DropdownOption[], cb: DropdownCallBack, selected_function?: SelectedFunc):\n HTMLDivElement {\n const options_wrapper = div(\"dropdown-options-wrapper\");\n const options_el = div(\"dropdown-options\");\n\n for (let i = 0; i < options.length; i++) {\n if (options[i].type === DropdownOptionType.Selection) {\n if (selected_function) {\n options[i].selected = selected_function(options[i]);\n } else {\n options[i].selected = options[i].label === selected_option;\n }\n const a = viewDropdownOption(options_el, options[i], cb);\n options_el.appendChild(a);\n } else if (options[i].type === DropdownOptionType.Divider) {\n const divider = div(\"dropdown-divider\");\n const rule = div(\"rule\");\n divider.appendChild(rule);\n if (options[i].label !== undefined && options[i].label.length > 0) {\n const span = document.createElement(\"span\");\n span.innerHTML = options[i].label;\n divider.appendChild(span);\n }\n options_el.appendChild(divider);\n }\n }\n options_wrapper.appendChild(options_el);\n return options_wrapper;\n}\n\nexport function viewDropdown(selected_option: string, options: DropdownOption[], cb: DropdownCallBack, selected_function?: SelectedFunc): HTMLDivElement {\n const class_name = \"view-attribute-dropdown\";\n const dropdown = div(class_name);\n const input = viewDropdownInputElement(selected_option);\n const options_wrapper = viewDropdownOptions(selected_option, options, function (option: DropdownOption) {\n input.value = option.label;\n input.innerHTML = option.label;\n cb(option);\n }, selected_function);\n const options_el = options_wrapper.getElementsByClassName(\"dropdown-options\")[0];\n const MAX_TOP = 45;\n const PADDING = 5;\n\n const adjustOptionsWrapper = function () {\n const wrapper_rect = options_wrapper.getBoundingClientRect();\n const options_rect = options_el.getBoundingClientRect();\n const input_rect = input.getBoundingClientRect();\n if ((options_rect.bottom < window.innerHeight) && (options_rect.bottom > wrapper_rect.bottom)) {\n options_wrapper.style.maxHeight = (options_rect.bottom - wrapper_rect.top) + \"px\";\n }\n if ((options_rect.bottom > window.innerHeight) && (wrapper_rect.top > MAX_TOP)) {\n const top = options_wrapper.style.top;\n let wt = 0;\n if (top) {\n wt = Number(top.slice(0, -2));\n }\n let step = options_wrapper.scrollTop;\n let new_offset = wt - step;\n const max_offset = MAX_TOP - input_rect.top;\n let hit_top: boolean = false;\n if (new_offset < max_offset) {\n new_offset = max_offset;\n step = new_offset - max_offset;\n hit_top = true;\n }\n if (new_offset > wt) {\n return; //this happens because of the stupid bounce in safari\n }\n options_wrapper.style.top = (new_offset) + \"px\";\n options_wrapper.scrollTop = 0;\n if (hit_top) { //we have a maxheight and step is 0 because it hit the top so get the full height using MAX_TOP\n options_wrapper.style.maxHeight = (window.innerHeight - MAX_TOP - PADDING) + \"px\";\n } else {\n let mh = 0;\n if (options_wrapper.style.maxHeight) {\n mh = Number(options_wrapper.style.maxHeight.slice(0, -2));\n }\n options_wrapper.style.maxHeight = (mh + step) + \"px\";\n }\n } else if (wrapper_rect.top <= MAX_TOP && options_rect.bottom > window.innerHeight) { //if it hits the top exactly on a scroll/nav\n options_wrapper.style.maxHeight = (window.innerHeight - wrapper_rect.top - PADDING) + \"px\";\n }\n };\n\n function openDropdown() {\n const right_panel = document.getElementById(\"right_col\");\n if (right_panel) {\n right_panel.classList.add(\"no-scroll\");\n }\n options_wrapper.style.top = \"\";\n options_wrapper.style.maxHeight = \"\";\n options_wrapper.classList.add(\"active\");\n let wrapper_rect = options_wrapper.getBoundingClientRect();\n let options_rect = options_el.getBoundingClientRect();\n const orig_top = wrapper_rect.top;\n let child_top = 0;\n for (let i = 0; i < options_el.childNodes.length; i++) {\n const child = options_el.childNodes[i] as HTMLElement;\n if (child.classList.contains(\"selected\")) {\n child.classList.add(\"hover\");\n let child_rect = child.getBoundingClientRect();\n let new_top = orig_top - child_rect.top;\n if (new_top + wrapper_rect.top > MAX_TOP) {\n options_wrapper.style.top = (new_top) + \"px\";\n } else {\n new_top = MAX_TOP - wrapper_rect.top;\n options_wrapper.style.top = (new_top) + \"px\";\n child_rect = child.getBoundingClientRect();\n child_top = child_rect.top;\n }\n break;\n }\n }\n wrapper_rect = options_wrapper.getBoundingClientRect();\n options_rect = options_el.getBoundingClientRect();\n if (wrapper_rect.bottom > window.innerHeight) {\n let h;\n if (options_rect.bottom < window.innerHeight) {\n h = options_rect.bottom - wrapper_rect.top - PADDING;\n } else {\n h = window.innerHeight - wrapper_rect.top - PADDING;\n }\n const need_to_scroll = child_top - orig_top;\n const room_to_scroll = options_wrapper.scrollHeight - h;\n if (need_to_scroll > room_to_scroll) {\n h = h - (need_to_scroll - room_to_scroll);\n }\n options_wrapper.style.maxHeight = h + \"px\";\n }\n options_wrapper.scrollTop = child_top - orig_top;\n }\n\n function keyNavDropdown(e: KeyboardEvent) {\n DropdownState.setKeyNavigation(true);\n let focused: HTMLElement | null;\n focused = null;\n for (let i = 0; i < options_el.childNodes.length; i++) {\n const child = options_el.childNodes[i] as HTMLElement;\n if (child.classList.contains(\"hover\")) {\n child.classList.remove(\"hover\");\n if (!focused) {\n let next_idx = -1;\n if (e.keyCode === 38) {\n next_idx = i - 1;\n } else {\n next_idx = i + 1;\n i++;\n }\n if (next_idx >= 0 && next_idx <= options_el.childNodes.length - 1) {\n focused = options_el.childNodes[next_idx] as HTMLElement;\n } else {\n focused = child;\n }\n }\n }\n }\n if (!focused) {\n focused = options_el.childNodes[0] as HTMLElement;\n for (let i = 0; i < options_el.childNodes.length; i++) {\n const child = options_el.childNodes[i] as HTMLElement;\n if (child.classList.contains(\"selected\")) {\n focused = child;\n focused.classList.add(\"hover\");\n }\n }\n }\n focused.classList.add(\"hover\");\n const rect = focused.getBoundingClientRect();\n\n if (rect.bottom >= window.innerHeight) {\n options_wrapper.scrollBy(0, (rect.bottom - window.innerHeight) + 2);\n adjustOptionsWrapper();\n }\n\n const wrapper_rect = options_wrapper.getBoundingClientRect();\n if (rect.top < wrapper_rect.top) {\n options_wrapper.scrollBy(0, rect.top - wrapper_rect.top);\n adjustOptionsWrapper();\n }\n }\n\n input.onclick = function () {\n DropdownState.setMenuFocused(true);\n openDropdown();\n };\n input.onblur = function () {\n DropdownState.setMenuFocused(false);\n const right_panel = document.getElementById(\"right_col\");\n if (right_panel) {\n right_panel.classList.remove(\"no-scroll\");\n }\n options_wrapper.classList.remove(\"active\");\n };\n\n dropdown.appendChild(input);\n options_wrapper.appendChild(options_el);\n dropdown.appendChild(options_wrapper);\n\n input.onkeydown = function (e) {\n if (e.keyCode === 27) {\n input.blur(); // close dropdown\n input.focus(); // refocus so keyboard to open dropdown works\n }\n if (e.keyCode === 13) {\n for (let i = 0; i < options_el.childNodes.length; i++) {\n const child = options_el.childNodes[i] as HTMLElement;\n if (child.classList.contains(\"hover\")) {\n child.click();\n break;\n }\n }\n }\n if (e.keyCode === 38 || e.keyCode === 40) { //up down\n if (options_wrapper.classList.contains(\"active\")) {\n keyNavDropdown(e);\n } else {\n openDropdown();\n }\n }\n };\n\n input.onkeyup = function (e) {\n if (e.keyCode === 38 || e.keyCode === 40) {\n DropdownState.setKeyNavigation(false);\n }\n };\n\n options_wrapper.onwheel = function () {\n adjustOptionsWrapper();\n };\n\n return dropdown;\n}\n", "import { div, span, anchor } from \"../../shared/dom\";\nimport { Overlay, OverlayStyle } from \"../../shared/overlay\";\nimport { ApiTeam, ApiTeamRole, ApiTeamAddUsersRequest, ApiUser } from \"./api_data\";\nimport { App } from \"./app\";\nimport { Ajax } from \"../../shared/ajax\";\nimport { v4 as uuid } from 'uuid';\nimport { DropdownOption, viewDropdown, DropdownOptionType } from \"../../shared/dropdown\";\n\nexport interface TeamForm {\n name_field: HTMLInputElement;\n container: HTMLDivElement;\n button: HTMLElement;\n}\n\nexport class Teams {\n\n static teamOverlayBody(): TeamForm {\n const d = div(\"overlay-panel-body\");\n d.style.maxWidth = (window.innerWidth - 200) + \"px\";\n\n const settings = div(\"settings-group\");\n const name = div(\"section\");\n const name_label = div(\"settings-label\");\n name_label.innerHTML = \"Team Name\";\n const name_value = div(\"settings-value\");\n const name_input = document.createElement(\"input\");\n name_input.value = \"\";\n name_value.appendChild(name_input);\n name.appendChild(name_label);\n name.appendChild(name_value);\n settings.appendChild(name);\n d.appendChild(settings);\n\n const panel_footer = div(\"overlay-panel-footer\");\n panel_footer.appendChild(div(\"spacer\"));\n const save_button = document.createElement(\"a\");\n save_button.classList.add(\"button\", \"noselect\");\n save_button.innerHTML = \"Create\";\n panel_footer.appendChild(save_button);\n d.appendChild(panel_footer);\n return {\n container: d,\n name_field: name_input,\n button: save_button,\n };\n }\n\n static newTeamOverlay(): Overlay {\n\n const body = Teams.teamOverlayBody();\n\n const save = function () {\n if (!/\\S/.test(body.name_field.value)) {\n return;\n }\n if (!App.user) {\n return;\n }\n const t: ApiTeam = {\n id: uuid(),\n owner_id: App.user.id,\n name: body.name_field.value,\n deleted_at: null,\n roles: [],\n };\n const url = \"/api/v1/teams/\" + t.id;\n Ajax.put(url, function (team: ApiTeam) {\n Overlay.close();\n App.teams.push(team);\n App.render();\n }, t);\n };\n\n body.name_field.onkeydown = function (e) {\n if (e.keyCode === 13) { // return\n save();\n }\n };\n\n body.button.onclick = function () {\n save();\n };\n\n const overlay = new Overlay(OverlayStyle.Viz, \"New Team\", [body.container], \"Create\", function () {\n save();\n }, undefined, function () {\n body.name_field.focus();\n });\n return overlay;\n }\n\n static editTeamOverlay(team: ApiTeam): Overlay {\n\n const body = this.teamOverlayBody();\n body.name_field.value = team.name;\n body.button.innerText = \"Update\";\n\n const save = function () {\n if (!/\\S/.test(body.name_field.value)) {\n return;\n }\n const changes: ApiTeam = {\n id: team.id,\n owner_id: team.owner_id,\n name: body.name_field.value,\n deleted_at: null,\n roles: [],\n };\n const url = \"/api/v1/teams/\" + changes.id;\n Ajax.put(url, function (updated_team: ApiTeam) {\n Overlay.close();\n for (let i = 0; i < App.teams.length; i++) {\n const el = App.teams[i];\n if (el.id === team.id) {\n App.teams[i] = updated_team;\n }\n }\n App.render();\n }, changes);\n };\n\n body.name_field.onkeydown = function (e) {\n if (e.keyCode === 13) { // return\n save();\n }\n };\n\n body.button.onclick = function () {\n save();\n };\n\n const overlay = new Overlay(OverlayStyle.Viz, \"Edit Team\", [body.container], \"Update\", function () {\n save();\n }, undefined, function () {\n body.name_field.focus();\n });\n return overlay;\n }\n\n static deleteTeamOverlay(team: ApiTeam): Overlay {\n const message = \"This will permanently delete the team \" + team.name + \". Everything in the team will also be deleted for all users.\";\n const confirm = \"To confirm, type the name of the team below.\";\n const overlay = Overlay.deleteConfirmByTypingOverlay(\"Delete Team\", message, confirm, team.name, function () {\n const changes: ApiTeam = {\n id: team.id,\n owner_id: team.owner_id,\n name: team.name,\n deleted_at: new Date().toISOString(),\n roles: [],\n };\n const url = \"/api/v1/teams/\" + team.id;\n Ajax.put(url, function () {\n Overlay.close();\n for (let i = 0; i < App.teams.length; i++) {\n const el = App.teams[i];\n if (el.id === team.id) {\n App.teams.splice(i, 1);\n }\n }\n const path = \"/viz\";\n history.pushState({}, \"\", path);\n App.router.match();\n }, changes);\n })\n return overlay;\n }\n\n static leaveTeamOverlay(team: ApiTeam, role: ApiTeamRole): Overlay {\n const d = div(\"overlay-panel-body\");\n d.style.maxWidth = (window.innerWidth - 200) + \"px\";\n\n const settings = div(\"message\");\n const message = document.createElement(\"p\");\n message.innerHTML = \"Are you sure you want to leave \" + team.name + \"? You will permamently lose access to everying in the team.\";\n settings.appendChild(message);\n d.appendChild(settings);\n\n const panel_footer = div(\"overlay-panel-footer\");\n const button = document.createElement(\"a\");\n button.classList.add(\"button\", \"noselect\", \"destructive\");\n panel_footer.appendChild(button);\n d.appendChild(panel_footer);\n\n const overlay = new Overlay(OverlayStyle.Viz, \"Leave Team\", [d], \"Leave team\", function () {\n const url = \"/api/v1/team_roles/\" + role.id;\n Ajax.delete(url, function () {\n //Overlay.clearAllOverlays();\n Overlay.close();\n for (let i = 0; i < App.teams.length; i++) {\n const el = App.teams[i];\n if (el.id === team.id) {\n App.teams.splice(i, 1);\n }\n }\n if (App.user) {\n App.selected_owner_id = App.user.id;\n }\n App.render();\n });\n });\n\n return overlay;\n }\n\n static addTeamMemberOverlay(team: ApiTeam, cb: Function): Overlay {\n\n const d = div(\"overlay-panel-body\");\n d.style.maxWidth = (window.innerWidth - 200) + \"px\";\n\n const group = div(\"settings-group\");\n const invite = div(\"section\", \"member-invite\");\n const email_input = document.createElement(\"input\");\n email_input.classList.add(\"email\");\n email_input.placeholder = \"Email\";\n invite.appendChild(email_input);\n\n const options_wrapper = div(\"member-permissions\");\n let role = \"Editor\";\n const render_selector = function (selected: string) {\n const options = [new DropdownOption(\"Admin\", 0), new DropdownOption(\"Editor\", 1)];\n const selector = viewDropdown(selected, options, function (option: DropdownOption) {\n selector.classList.remove(\"active\");\n role = option.label;\n render_selector(role);\n });\n options_wrapper.innerHTML = \"\";\n options_wrapper.appendChild(selector);\n };\n\n render_selector(role);\n invite.appendChild(options_wrapper);\n\n group.appendChild(invite);\n d.appendChild(group);\n\n const panel_footer = div(\"overlay-panel-footer\");\n panel_footer.appendChild(div(\"spacer\"));\n const button = document.createElement(\"a\");\n button.classList.add(\"button\", \"noselect\");\n button.innerHTML = \"Send Invite\";\n panel_footer.appendChild(button);\n d.appendChild(panel_footer);\n\n const send = function () {\n if (button.classList.contains(\"disabled\")) {\n return;\n }\n button.classList.add(\"disabled\");\n button.innerHTML = \"Sending...\";\n const add: ApiTeamAddUsersRequest = {\n email: email_input.value,\n role: role,\n };\n const url = \"/api/v1/teams/\" + team.id + \"/add_users\";\n Ajax.post(url, function (data: ApiTeamRole[]) {\n for (const r of data) {\n for (const t of App.teams) {\n if (t.id === team.id) {\n t.roles.push(r);\n }\n }\n }\n Overlay.close();\n cb(data);\n }, [add], function () {\n button.classList.remove(\"disabled\");\n button.innerHTML = \"Send\";\n });\n };\n\n button.onclick = function () {\n send();\n }\n\n const overlay = new Overlay(OverlayStyle.Viz, \"Add member\", [d], \"Send Invite\", function () {\n }, undefined, function () {\n email_input.focus();\n });\n return overlay;\n }\n\n static userIsAdmin(user: ApiUser | null, team: ApiTeam): boolean {\n if (!user) {\n return false;\n }\n for (const r of team.roles) {\n if (r.user_id === user.id && r.role === \"Admin\") {\n return true;\n }\n }\n return false;\n }\n\n static teamMembersOverlay(team: ApiTeam): Overlay {\n const d = div(\"overlay-panel-body\", \"team-member-list\");\n d.style.maxWidth = (window.innerWidth - 300) + \"px\";\n\n const settings = div(\"settings-group\");\n const header = div(\"team-row\", \"team-row-header\");\n const title_name = div(\"member-info\");\n title_name.innerHTML = \"Member\";\n const title_role = div(\"permissions-info\");\n title_role.innerHTML = \"Permissions\";\n header.appendChild(title_name);\n header.appendChild(title_role);\n settings.appendChild(header);\n\n const is_admin = Teams.userIsAdmin(App.user, team);\n\n const add_member_row = function (r: ApiTeamRole) {\n const row = div(\"team-row\");\n const info = div(\"member-info\");\n const user_info = div(\"team-member\");\n const img = div(\"img\");\n if (r.user && r.user.image_timestamp !== null) {\n // TODO\n //const url = r.user.uploaded_avatar;\n //img.style.backgroundImage = \"url(\" + url + \")\";\n }\n user_info.appendChild(img);\n const name = div(\"name\");\n name.innerHTML = r.email;\n if (App.user && r.user_id === App.user.id) {\n const s = span();\n s.innerHTML = \" (You)\";\n name.appendChild(s);\n }\n if (r.pending) {\n const s = span();\n s.innerHTML = \" (Pending)\";\n name.appendChild(s);\n }\n user_info.appendChild(name);\n info.appendChild(user_info);\n row.appendChild(info);\n\n const permissions = div(\"permissions-info\");\n const is_owner = r.user_id === team.owner_id;\n const options_wrapper = div(\"member-permissions\");\n let role = is_owner ? \"Owner\" : r.role;\n const render_selector = function (selected: string) {\n const options = [new DropdownOption(\"Admin\", 0), new DropdownOption(\"Editor\", 1), new DropdownOption(\"\", -1, DropdownOptionType.Divider), new DropdownOption(\"Remove\", 2)];\n const selector = viewDropdown(selected, options, function (option: DropdownOption) {\n if (option.value === 0 || option.value === 1) {\n // update\n const change: ApiTeamRole = {\n id: r.id,\n team_id: r.team_id,\n user_id: r.user_id,\n user: null,\n pending: r.pending,\n email: r.email,\n role: option.label,\n };\n const url = \"/api/v1/team_roles/\" + r.id;\n Ajax.put(url, function () {\n selector.classList.remove(\"active\");\n role = option.label;\n render_selector(role);\n for (const t of App.teams) {\n if (t.id === team.id) {\n for (let i = 0; i < t.roles.length; i++) {\n const el = t.roles[i];\n if (el.id === r.id) {\n t.roles[i].role = option.label;\n }\n }\n }\n }\n }, change);\n } else if (option.value === 2) {\n // remove\n const url = \"/api/v1/team_roles/\" + r.id;\n Ajax.delete(url, function () {\n for (const t of App.teams) {\n if (t.id === team.id) {\n for (let i = 0; i < t.roles.length; i++) {\n const el = t.roles[i];\n if (el.id === r.id) {\n t.roles.splice(i, 1);\n }\n }\n }\n }\n if (row.parentElement) {\n row.parentElement.removeChild(row);\n }\n //Api.getUser();\n });\n }\n });\n options_wrapper.innerHTML = \"\";\n options_wrapper.appendChild(selector);\n\n if (!is_admin || is_owner) {\n const input = selector.querySelector(\"input\");\n if (input) {\n input.disabled = true;\n }\n }\n if (App.user && App.user.id === r.user_id && !is_owner) {\n const leave = anchor(\"team-leave\");\n leave.innerHTML = \"Leave team\";\n options_wrapper.appendChild(leave);\n\n leave.onclick = function (e) {\n e.preventDefault();\n Teams.leaveTeamOverlay(team, r);\n };\n }\n };\n\n render_selector(role);\n permissions.appendChild(options_wrapper);\n\n row.appendChild(permissions);\n settings.appendChild(row);\n };\n\n for (const role of team.roles) {\n add_member_row(role);\n }\n d.appendChild(settings);\n\n const panel_footer = div(\"overlay-panel-footer\", \"team-footer\");\n\n if (is_admin) {\n const add_member_wrapper = div(\"add-team-member\");\n const add_member = div(\"team-member\");\n const add_img = div(\"img\");\n add_img.innerHTML = \"+\";\n add_member.appendChild(add_img);\n const add_name = div(\"name\");\n add_name.innerHTML = \"Add member\";\n add_member.appendChild(add_name);\n add_member_wrapper.appendChild(add_member);\n panel_footer.appendChild(add_member_wrapper);\n\n const space = div(\"spacer\");\n panel_footer.appendChild(space);\n\n add_member.onclick = function () {\n Teams.addTeamMemberOverlay(team, function (roles: ApiTeamRole[]) {\n for (const r of roles) {\n add_member_row(r);\n }\n });\n };\n }\n\n const button = document.createElement(\"a\");\n button.classList.add(\"button\", \"noselect\");\n button.innerHTML = \"Done\";\n button.onclick = function () {\n Overlay.close();\n };\n panel_footer.appendChild(button);\n d.appendChild(panel_footer);\n\n const overlay = new Overlay(OverlayStyle.Viz, team.name, [d], \"Done\", function () {\n Overlay.close();\n });\n overlay.panel.classList.add(\"flex-width\");\n\n return overlay;\n }\n\n}", "import { Overlay, OverlayStyle } from \"../../shared/overlay\";\nimport { div, anchor, textnode, span } from \"../../shared/dom\";\nimport { App } from \"./app\";\nimport { Loading } from \"../../shared/loading\";\nimport { Ajax } from \"../../shared/ajax\";\nimport { ApiBQConnection, ApiBQTable } from \"./api_data\";\nimport { timeAgoDateFormat } from \"../../shared/date_format\";\n\nexport class Upload {\n\n static bytesSizeDescription(bytes: number) {\n const n = 1000;\n const units = Math.floor(Math.log(bytes) / Math.log(n));\n switch (units) {\n case 0:\n return bytes + \" bytes\";\n case 1:\n return Math.round(bytes / n) + \" KB\";\n default:\n return (bytes / (n * n)).toFixed(1) + \" MB\";\n }\n }\n\n static info_row(label: string, value: string): HTMLDivElement {\n const d = div(\"info-row\");\n const l = div(\"info-label\");\n l.innerText = label;\n const val = div(\"info-val\");\n val.title = value;\n val.innerText = value;\n d.appendChild(l);\n d.appendChild(val);\n return d;\n }\n\n static input(owner_id: string): HTMLInputElement {\n const input = document.createElement(\"input\");\n input.classList.add(\"upload\");\n input.id = \"file-input\";\n input.setAttribute(\"name\", \"file\");\n input.setAttribute(\"type\", \"file\");\n input.setAttribute(\"accept\", \"text/csv, .csv\");\n input.onchange = function () {\n\n let file: File;\n const reader = new FileReader();\n reader.onload = function () {\n if (reader.result && typeof reader.result === \"string\" && App.user) {\n const preview = div(\"overlay-panel-body\");\n const info = div(\"upload-info\");\n const label = document.createElement(\"h3\");\n label.innerText = file.name;\n info.appendChild(label);\n\n const date = Upload.info_row(\"Modified\", new Date(file.lastModified).toLocaleString());\n info.appendChild(date);\n\n const size = Upload.info_row(\"Filesize\", Upload.bytesSizeDescription(file.size));\n info.appendChild(size);\n\n const lines = reader.result.split(\"\\n\");\n const rows = Upload.info_row(\"Rows\", lines.length.toLocaleString());\n info.appendChild(rows);\n preview.appendChild(info);\n\n const footer = div(\"overlay-panel-footer\");\n footer.appendChild(div(\"spacer\"));\n const button = document.createElement(\"a\");\n button.classList.add(\"button\", \"noselect\");\n button.innerHTML = \"Upload\";\n\n const loading = Loading.overlay();\n button.appendChild(loading);\n\n footer.appendChild(button);\n preview.appendChild(footer);\n\n new Overlay(OverlayStyle.Viz, \"Upload CSV\", [preview], \"\", function () {\n //\n });\n\n button.onclick = function () {\n if (button.classList.contains(\"working\") || reader.result === null) {\n return;\n }\n button.classList.add(\"working\");\n Overlay.disableDismissal();\n\n const blob = new Blob([reader.result], {});\n const data = new FormData();\n data.append(\"file\", blob, file.name);\n Ajax.post(\"/api/v1/bq_upload?owner_id=\" + owner_id, function (data: ApiBQTable[]) {\n App.build_table_sets(data);\n App.render();\n Overlay.enableDismissal();\n Overlay.close();\n }, data, function () {\n button.classList.remove(\"working\");\n Overlay.enableDismissal();\n });\n }\n }\n };\n if (input.files && input.files.length > 0) {\n reader.readAsText(input.files[0]);\n file = input.files[0];\n }\n input.value = \"\";\n };\n return input;\n }\n\n static show_key_upload_overlay() {\n const body = div(\"overlay-panel-body\");\n\n const desc = div(\"overlay-desc\");\n desc.innerHTML = \"To connect to Google BigQuery, upload a JSON service account key. \";\n const link = anchor();\n link.innerText = \"How to create a service account key \u2192\";\n desc.appendChild(link);\n body.appendChild(desc);\n\n const prompt = div();\n body.appendChild(prompt);\n const info = div(\"upload-info\", \"upload-key\");\n body.appendChild(info);\n\n const input = document.createElement(\"input\");\n input.classList.add(\"upload\");\n input.id = \"file-input\";\n input.setAttribute(\"name\", \"file\");\n input.setAttribute(\"type\", \"file\");\n input.setAttribute(\"accept\", \"text/json, .json\");\n desc.appendChild(input);\n\n input.onchange = function () {\n let file: File;\n const reader = new FileReader();\n reader.onload = function () {\n if (reader.result && typeof reader.result === \"string\") {\n render_info(file, reader.result);\n }\n }\n if (input.files && input.files.length > 0) {\n reader.readAsText(input.files[0]);\n file = input.files[0];\n }\n\n input.value = \"\";\n }\n\n const render_prompt = function (error_string: string) {\n prompt.innerHTML = \"\";\n info.innerHTML = \"\";\n\n if (error_string) {\n const err = div(\"error\");\n err.innerHTML = error_string;\n prompt.appendChild(err);\n }\n\n const footer = div(\"overlay-panel-footer\");\n footer.appendChild(div(\"spacer\"));\n const button = document.createElement(\"a\");\n button.classList.add(\"button\", \"noselect\");\n button.innerHTML = \"Choose File\";\n\n const loading = Loading.overlay();\n button.appendChild(loading);\n\n button.onclick = function () {\n input.click();\n }\n\n footer.appendChild(button);\n prompt.appendChild(footer);\n }\n\n const render_info = function (file: File, file_text: string) {\n prompt.innerHTML = \"\";\n info.innerHTML = \"\";\n\n const d = JSON.parse(file_text);\n if (d.type === undefined || d.type !== \"service_account\" || d.project_id === undefined || d.client_email === undefined) {\n render_prompt(\"\" + file.name + \" doesn't appear to be a service account key.\");\n return;\n }\n\n const label = document.createElement(\"h3\");\n label.innerText = file.name;\n info.appendChild(label);\n\n const info_rows = div();\n const date = Upload.info_row(\"Modified\", new Date(file.lastModified).toLocaleString());\n info_rows.appendChild(date);\n\n const id = Upload.info_row(\"Project ID\", d.project_id);\n info_rows.appendChild(id);\n\n const size = Upload.info_row(\"Email\", d.client_email);\n info_rows.appendChild(size);\n info.appendChild(info_rows);\n\n const footer = div(\"overlay-panel-footer\");\n const button = document.createElement(\"a\");\n button.classList.add(\"button\", \"noselect\");\n button.innerHTML = \"Connect\";\n\n const loading = Loading.overlay();\n button.appendChild(loading);\n\n const select_link = anchor();\n select_link.innerText = \"Choose a different file\";\n select_link.href = \"#\";\n select_link.onclick = function (e) {\n input.click();\n e.preventDefault();\n }\n footer.appendChild(select_link);\n footer.appendChild(div(\"spacer\"));\n footer.appendChild(button);\n info.appendChild(footer);\n\n button.onclick = function () {\n if (button.classList.contains(\"working\")) {\n return;\n }\n button.classList.add(\"working\");\n Overlay.disableDismissal();\n\n const blob = new Blob([file_text], {});\n const data = new FormData();\n data.append(\"file\", blob, file.name);\n const owner_id = App.selected_owner_id;\n const path = \"/api/v1/bq_connections?owner_id=\" + owner_id + \"&g_project_id=\" + d.project_id + \"&g_email=\" + d.client_email;\n Ajax.post(path, function (data: ApiBQTable[]) {\n console.log(data);\n App.build_table_sets(data);\n App.render();\n Overlay.enableDismissal();\n Overlay.close();\n }, data, function () {\n button.classList.remove(\"working\");\n Overlay.enableDismissal();\n });\n }\n }\n\n render_prompt(\"\");\n\n new Overlay(OverlayStyle.Viz, \"Connect to BigQuery\", [body], \"\", function () {\n //\n });\n\n\n }\n\n static show_refresh_overlay(owner_id: string) {\n const body = div();\n const loading_contain = div(\"data-preview\", \"loading\");\n const loading_el = Loading.overlay();\n loading_contain.appendChild(loading_el);\n body.appendChild(loading_contain);\n\n const list_contain = div();\n list_contain.style.display = \"none\";\n const list = div(\"conn-list\");\n list_contain.appendChild(list);\n\n const footer = div(\"overlay-panel-footer\");\n const spacer = div(\"spacer\", \"light-text\");\n footer.appendChild(spacer);\n const button = document.createElement(\"a\");\n button.classList.add(\"button\", \"noselect\");\n button.innerHTML = \"Refresh Schemas\";\n const loading = Loading.overlay();\n button.appendChild(loading);\n footer.appendChild(button);\n list_contain.appendChild(footer);\n body.appendChild(list_contain);\n\n button.onclick = function () {\n button.classList.add(\"working\");\n spacer.innerText = \"\";\n Ajax.post(\"/api/v1/bq_connections/\" + owner_id + \"/refresh\", function () {\n App.get_user_data(function () {\n button.classList.remove(\"working\");\n spacer.innerText = \"Table schemas updated.\";\n App.render();\n });\n }, undefined, function () {\n button.classList.remove(\"working\");\n })\n }\n\n const render_list = function (data: ApiBQConnection[]) {\n for (const c of data) {\n const d = div(\"conn\", \"light-text\");\n const label = document.createElement(\"h3\");\n label.innerText = c.file_name;\n d.appendChild(label);\n const info = div();\n info.innerText = c.project_id;\n const dot = span(\"dot\");\n dot.innerText = \" \u2022 \";\n info.appendChild(dot);\n const updated = timeAgoDateFormat(new Date(c.created_at));\n info.appendChild(textnode(updated));\n d.appendChild(info);\n list.appendChild(d);\n }\n loading_contain.style.display = \"none\";\n list_contain.style.display = \"block\";\n }\n\n Ajax.get(\"/api/v1/bq_connections/\" + owner_id, function (data: ApiBQConnection[]) {\n render_list(data);\n });\n\n new Overlay(OverlayStyle.Viz, \"Edit Connections\", [body], \"\", function () {\n //\n });\n }\n\n}", "\nimport { div, h2, anchor, form, button, br, textnode } from \"../../shared/dom\";\nimport { SVG } from \"../../shared/svg\";\nimport { App } from \"./app\";\nimport { Loading } from \"../../shared/loading\";\nimport { ApiErrorResponse, ApiLoginRequest, ApiUser, ApiInviteRequest, ApiActivateRequest } from \"./api_data\";\nimport { Ajax } from \"../../shared/ajax\";\n\nexport class Auth {\n\n static input(placeholder: string, autocomplete: string, type: string, name: string): HTMLInputElement {\n const i = App.input();\n i.placeholder = placeholder;\n i.spellcheck = false;\n if (autocomplete !== \"\") {\n i.autocomplete = autocomplete;\n }\n i.autocapitalize = \"off\";\n i.type = type;\n if (name !== \"\") {\n i.name = name;\n }\n return i;\n }\n\n static render_signup(root: HTMLElement) {\n root.innerHTML = \"\";\n const d = div(\"h-100\", \"c-flex\");\n const frame = div(\"h-100\", \"c-flex\", \"top\");\n d.appendChild(frame);\n\n const top = div(\"c-flex\");\n const h = h2();\n h.innerText = \"Request Access\";\n top.appendChild(h);\n const message = div(\"msg\", \"txt-c\");\n message.innerText = \"Enter your email to join the waitlist.\";\n message.appendChild(br());\n message.appendChild(textnode(\"Already have an account? \"));\n const link = anchor();\n link.innerText = \"Sign In.\";\n link.href = \"/login\";\n App.enable_link(link);\n message.appendChild(link);\n top.appendChild(message);\n\n frame.appendChild(top);\n\n const bottom = div(\"footer-buttons\");\n const f = form();\n bottom.appendChild(f);\n\n const email = Auth.input(\"Email\", \"email\", \"text\", \"email\");\n f.appendChild(email);\n\n const sign_up = button(\"key\");\n sign_up.innerText = \"Join Waitlist\";\n\n const loading = Loading.overlay();\n sign_up.appendChild(loading);\n\n const send = function () {\n if (email.value === \"\") {\n return;\n }\n sign_up.classList.add(\"working\");\n sign_up.disabled = true;\n error.style.display = \"none\";\n confirm.style.display = \"none\";\n const req: ApiInviteRequest = {\n email: email.value\n }\n Ajax.post(\"/api/v1/request_invite\", function () {\n confirm.style.display = \"block\";\n email.value = \"\";\n sign_up.classList.remove(\"working\");\n sign_up.disabled = false;\n }, req, function (_: number, data: ApiErrorResponse) {\n if (data.message !== undefined) {\n console.log(data.message);\n error.innerHTML = data.message;\n error.style.display = \"block\";\n }\n sign_up.disabled = false;\n sign_up.classList.remove(\"working\");\n });\n }\n\n sign_up.onclick = function () {\n send();\n }\n\n f.onsubmit = function (e) {\n e.preventDefault();\n send();\n }\n\n f.appendChild(sign_up);\n const error = div(\"msg\", \"error\");\n error.style.display = \"none\";\n bottom.appendChild(error);\n const confirm = div(\"msg\", \"txt-c\");\n confirm.style.display = \"none\";\n confirm.innerText = \"Thanks! Your email has been added to the waitlist.\";\n bottom.appendChild(confirm);\n frame.appendChild(bottom);\n\n root.appendChild(d);\n email.focus();\n }\n\n static render_activate(root: HTMLElement, token: string) {\n root.innerHTML = \"\";\n const d = div(\"h-100\", \"c-flex\");\n const frame = div(\"h-100\", \"c-flex\", \"top\");\n d.appendChild(frame);\n\n const top = div(\"c-flex\");\n top.appendChild(SVG.logo(\"logo-small\"));\n const h = h2();\n h.innerText = \"Create your Account\";\n top.appendChild(h);\n const message = div(\"msg\");\n message.appendChild(textnode(\"Already have an account? \"));\n const link = anchor();\n link.innerText = \"Sign In.\";\n link.href = \"/login\";\n App.enable_link(link);\n message.appendChild(link);\n top.appendChild(message);\n\n frame.appendChild(top);\n\n const bottom = div(\"footer-buttons\");\n const f = form(\"v\");\n bottom.appendChild(f);\n\n const error = div(\"msg\", \"error\");\n error.style.display = \"none\";\n bottom.appendChild(error);\n\n const email = Auth.input(\"Email\", \"email\", \"text\", \"email\");\n f.appendChild(email);\n\n const pass = Auth.input(\"Password\", \"new-password\", \"password\", \"password\");\n f.appendChild(pass);\n\n const sign_up = button(\"key\");\n sign_up.innerText = \"Sign Up\";\n sign_up.disabled = true;\n sign_up.style.opacity = \"0.4\";\n\n const loading = Loading.overlay();\n sign_up.appendChild(loading);\n\n const show_error = function (message: string) {\n error.innerHTML = message;\n error.style.display = \"block\";\n }\n\n const hide_error = function () {\n error.innerHTML = \"\";\n error.style.display = \"none\";\n }\n\n const check_lengths = function () {\n if (email.value.length < 1 || pass.value.length < 6) {\n sign_up.style.opacity = \"0.4\";\n sign_up.disabled = true;\n } else {\n sign_up.style.opacity = \"1\";\n sign_up.disabled = false;\n }\n }\n\n const x = \"x\";\n const add_events = function (i: HTMLInputElement, min_length: number) {\n i.onfocus = function () {\n i.classList.remove(x);\n hide_error();\n }\n i.onblur = function () {\n if (i.value.length < min_length) {\n i.classList.add(x);\n }\n }\n i.oninput = function () {\n check_lengths();\n }\n }\n\n add_events(email, 1);\n add_events(pass, 6);\n\n const send = function () {\n if (email.value.length < 1 || pass.value.length < 6) {\n return;\n }\n sign_up.classList.add(\"working\");\n sign_up.disabled = true;\n const req: ApiActivateRequest = {\n email: email.value,\n token: token,\n password: pass.value,\n }\n\n const on_success = function (_d: ApiUser) {\n // TODO: load data\n App.navigate(\"/\");\n }\n\n const on_error = function (_: number, data: ApiErrorResponse) {\n if (data.message !== undefined) {\n show_error(data.message);\n console.log(data.message);\n }\n sign_up.disabled = false;\n sign_up.classList.remove(\"working\");\n }\n\n Ajax.post(\"/api/v1/activate\", on_success, req, on_error);\n }\n\n sign_up.onclick = function () {\n send();\n }\n\n f.onsubmit = function (e) {\n e.preventDefault();\n send();\n }\n\n f.appendChild(sign_up);\n frame.appendChild(bottom);\n\n const terms = div(\"msg\", \"txt-c\");\n terms.style.marginTop = \"16px\";\n terms.innerText = \"By signing up you acknowledge that you have read, and agree to our \"\n const terms_link = anchor();\n terms_link.innerText = \"Terms of Service\";\n terms.appendChild(terms_link);\n terms.appendChild(textnode(\" and \"));\n const privacy_link = anchor();\n privacy_link.innerText = \"Privacy Policy.\";\n terms.appendChild(privacy_link);\n bottom.appendChild(terms);\n\n root.appendChild(d);\n email.focus();\n }\n\n static render_login(root: HTMLElement) {\n root.innerHTML = \"\";\n const d = div(\"h-100\", \"c-flex\");\n const frame = div(\"h-100\", \"c-flex\", \"top\");\n d.appendChild(frame);\n\n const top = div(\"c-flex\");\n const logo = anchor();\n logo.appendChild(SVG.logo(\"logo-small\"));\n logo.href = \"/\";\n top.appendChild(logo);\n const h = h2();\n h.innerText = \"Welcome Back\";\n top.appendChild(h);\n const message = div(\"msg\", \"txt-c\");\n message.innerText = \"Don't have an account? \";\n const link = anchor();\n link.innerText = \"Sign Up.\";\n link.href = \"/\";\n message.appendChild(link);\n top.appendChild(message);\n frame.appendChild(top);\n\n App.enable_link(link);\n\n const bottom = div(\"footer-buttons\");\n const f = form();\n bottom.appendChild(f);\n\n const email = Auth.input(\"Email\", \"email\", \"text\", \"email\");\n f.appendChild(email);\n\n email.onkeydown = function (e) {\n console.log(e);\n }\n\n const pass = App.input();\n pass.placeholder = \"Password\";\n pass.type = \"password\";\n pass.autocomplete = \"current-password\";\n f.appendChild(pass);\n\n const sign_in = button(\"key\");\n sign_in.innerText = \"Log In\";\n\n const loading = Loading.overlay();\n sign_in.appendChild(loading);\n\n f.appendChild(sign_in);\n\n const error = div(\"msg\", \"error\");\n error.style.display = \"none\";\n bottom.appendChild(error);\n frame.appendChild(bottom);\n\n root.appendChild(d);\n email.focus();\n\n const login_ok = function (_d: ApiUser) {\n App.get_user_data(function () {\n App.navigate(\"/\");\n });\n }\n\n const login_fail = function (_: number, data: ApiErrorResponse) {\n if (data.message !== undefined) {\n console.log(data.error);\n error.innerHTML = data.message;\n error.style.display = \"block\";\n }\n sign_in.disabled = false;\n sign_in.classList.remove(\"working\");\n }\n\n const login = function () {\n if (email.value.length < 1 || pass.value.length < 1) {\n return;\n }\n sign_in.classList.add(\"working\");\n const req: ApiLoginRequest = {\n email: email.value,\n password: pass.value,\n }\n sign_in.disabled = true;\n error.style.display = \"none\";\n Ajax.post(\"/api/v1/login\", login_ok, req, login_fail);\n }\n\n f.onsubmit = function (e) {\n e.preventDefault();\n login();\n }\n\n sign_in.onclick = function (e) {\n e.preventDefault();\n login();\n }\n }\n\n}", "import { ApiChangeEmailRequest, ApiErrorResponse, ApiUser, ApiUserUpdate } from \"./api_data\";\nimport { div, input, anchor, form, button } from \"../../shared/dom\";\nimport { SVG } from \"../../shared/svg\";\nimport { Loading } from \"../../shared/loading\";\nimport { Ajax } from \"../../shared/ajax\";\nimport { Auth } from \"./auth\";\nimport { Overlay, OverlayStyle } from \"../../shared/overlay\";\nimport { App } from \"./app\";\nimport { FilesPage } from \"./files_page\";\n\nexport class Settings {\n\n private static edit_section(title: string): HTMLElement {\n const section = div(\"block\", title.toLowerCase().replace(/ /g, \"-\"));\n const title_el = div(\"medium\", \"title\");\n title_el.innerText = title;\n section.appendChild(title_el);\n return section;\n }\n\n static render_profile_settings(user: ApiUser, container: HTMLElement) {\n const d = div(\"settings\");\n const avatar = Settings.edit_section(\"Avatar\");\n d.appendChild(avatar);\n\n const img = div(\"user-avatar\");\n if (user.image_timestamp) {\n const url = FilesPage.avatar_url(user);\n img.style.backgroundImage = \"url(\" + url + \")\";\n }\n avatar.appendChild(img);\n\n const edit_overlay = div(\"avatar-edit\", \"c-flex\");\n const pencil = SVG.pencil();\n edit_overlay.appendChild(pencil);\n img.appendChild(edit_overlay);\n\n const loading_img = document.createElement(\"img\");\n loading_img.classList.add(\"loading-img\", \"loading-img-light\");\n loading_img.src = Loading.img_light;\n edit_overlay.appendChild(loading_img);\n\n const picker = input();\n picker.setAttribute(\"type\", \"file\");\n picker.setAttribute(\"accept\", \"image/png,image/jpeg,image/gif,image/jpg\");\n edit_overlay.appendChild(picker);\n\n let img_src = \"\";\n picker.onchange = function () {\n const reader = new FileReader();\n const bin_reader = new FileReader();\n\n reader.onload = function () {\n const result = reader.result;\n if (result !== null && typeof result === 'string') {\n img_src = result;\n }\n };\n\n bin_reader.onload = function () {\n const result = bin_reader.result;\n if (result !== null && result instanceof ArrayBuffer) {\n const form = new FormData();\n const blob = new Blob([result], {});\n form.append(\"file\", blob);\n edit_overlay.classList.add(\"loading\");\n Ajax.post(\"/api/v1/user_avatar\", function (data: ApiUser) {\n if (App.user) {\n App.user.image_timestamp = data.image_timestamp;\n }\n edit_overlay.classList.remove(\"loading\");\n img.style.backgroundImage = \"url(\" + img_src + \")\";\n const header_img = document.querySelector(\"div.fixed-header div.user-avatar\") as HTMLElement;\n if (header_img) {\n const url = FilesPage.avatar_url(data);\n header_img.style.backgroundImage = \"url(\" + url + \")\";\n }\n }, form);\n }\n };\n if (picker.files && picker.files.length > 0) {\n reader.readAsDataURL(picker.files[0]);\n bin_reader.readAsArrayBuffer(picker.files[0]);\n }\n }\n\n img.onclick = function () {\n picker.click();\n }\n\n const name_section = Settings.edit_section(\"Name\");\n d.appendChild(name_section);\n\n const name_el = div();\n name_el.innerText = user.name;\n name_section.appendChild(name_el);\n const name_link = anchor(\"inline-block\");\n name_link.innerText = \"Change name\";\n name_section.appendChild(name_link);\n\n name_link.onclick = function () {\n const body = div(\"overlay-body\");\n new Overlay(OverlayStyle.Viz, \"Change Name\", [body], \"\", function () {\n //\n });\n\n const f = form();\n const name_input = Auth.input(\"Name\", \"false\", \"text\", \"\");\n name_input.value = user.name;\n f.appendChild(name_input);\n\n const err = div(\"error\");\n err.style.display = \"none\";\n f.appendChild(err);\n\n const button_container = div(\"r-align\");\n const update = button(\"key\");\n button_container.appendChild(update);\n update.setAttribute(\"type\", \"submit\");\n update.innerText = \"Update\";\n const loading = Loading.overlay();\n update.appendChild(loading);\n f.appendChild(button_container);\n body.appendChild(f);\n\n f.onsubmit = function (e) {\n e.preventDefault();\n if (update.classList.contains(\"working\")) {\n return;\n }\n update.classList.add(\"working\");\n err.style.display = \"none\";\n const req: ApiUserUpdate = {\n name: name_input.value\n }\n Ajax.post(\"/api/v1/user_update\", function (data: ApiUser) {\n if (App.user) {\n App.user.name = data.name;\n }\n name_el.innerText = data.name;\n Overlay.close();\n App.render();\n }, req, function (_code: number, data: ApiErrorResponse) {\n update.classList.remove(\"working\");\n if (data.message !== undefined) {\n err.style.display = \"block\";\n err.innerText = data.message;\n }\n })\n }\n\n name_input.focus();\n }\n\n const email_section = Settings.edit_section(\"Email\");\n d.appendChild(email_section);\n\n const email_el = div();\n email_el.innerText = user.email;\n email_section.appendChild(email_el);\n const email_link = anchor(\"inline-block\");\n email_link.innerText = \"Change email\";\n email_section.appendChild(email_link);\n\n email_link.onclick = function () {\n const body = div(\"overlay-body\");\n new Overlay(OverlayStyle.Viz, \"Change Email\", [body], \"\", function () {\n //\n });\n\n const f = form();\n const email_input = Auth.input(\"Email\", \"false\", \"text\", \"\");\n email_input.value = user.email;\n f.appendChild(email_input);\n\n const pass_input = Auth.input(\"Password\", \"false\", \"password\", \"\");\n f.appendChild(pass_input);\n\n const err = div(\"error\");\n err.style.display = \"none\";\n f.appendChild(err);\n\n const button_container = div(\"r-align\");\n const update = button(\"key\");\n button_container.appendChild(update);\n update.setAttribute(\"type\", \"submit\");\n update.innerText = \"Update\";\n const loading = Loading.overlay();\n update.appendChild(loading);\n f.appendChild(button_container);\n body.appendChild(f);\n\n f.onsubmit = function (e) {\n e.preventDefault();\n if (update.classList.contains(\"working\")) {\n return;\n }\n err.style.display = \"none\";\n update.classList.add(\"working\");\n const req: ApiChangeEmailRequest = {\n email: user.email,\n password: pass_input.value,\n new_email: email_input.value,\n }\n Ajax.post(\"/api/v1/user_email_update\", function (data: ApiUser) {\n if (App.user) {\n App.user.email = data.email;\n }\n email_el.innerText = data.email;\n App.render();\n Overlay.close();\n }, req, function (_code: number, data: ApiErrorResponse) {\n update.classList.remove(\"working\");\n if (data.message !== undefined) {\n err.style.display = \"block\";\n err.innerText = data.message;\n }\n })\n }\n\n email_input.focus();\n }\n\n container.appendChild(d);\n }\n}", "import { ApiTeam, ApiBQResponse, ApiVizPageCreateRequest, ApiPage, ApiBQQuery, ApiUser } from \"./api_data\";\nimport { Teams } from \"./teams\";\nimport { div, span, anchor, textnode } from \"../../shared/dom\";\nimport { App } from \"./app\";\nimport { Overlay, OverlayStyle } from \"../../shared/overlay\";\nimport { Ajax } from \"../../shared/ajax\";\nimport { Loading } from \"../../shared/loading\";\nimport { DropdownState } from \"../../shared/dropdown\";\nimport { Upload } from \"./upload\";\nimport uuid = require(\"uuid\");\nimport { timeAgoDateFormat } from \"../../shared/date_format\";\nimport { Menu } from \"../../shared/menu\";\nimport { VizSVG } from \"./viz_svg\";\nimport { SVG } from \"../../shared/svg\";\nimport { Settings } from \"./settings\";\nimport { Graph } from \"../../shared/graph\";\n\nexport interface SectionHeader {\n button: HTMLElement;\n container: HTMLElement;\n}\n\nexport interface VizListOpts {\n show_menu: boolean;\n columns: number;\n}\n\nexport class FilesPage {\n\n static render_data_links(container: HTMLElement) {\n\n let empty = true;\n if (App.table_sets[App.selected_owner_id] !== undefined) {\n for (const table of App.table_sets[App.selected_owner_id]) {\n const is_upload = table.project_id === \"daytum-viz\";\n empty = false;\n const t = div(\"data-link\");\n t.innerText = table.id;\n t.appendChild(VizSVG.large_table_icon());\n const count = div(\"count\");\n count.innerText = Graph.compact_number(table.row_count);\n t.appendChild(count);\n const label = div(\"meta\");\n const date = new Date(table.creation_time);\n const updated = timeAgoDateFormat(date);\n const dataset = is_upload ? \"Import\" : table.dataset_id;\n const dot = span(\"dot\");\n dot.innerText = \" \u2022 \";\n label.innerText = dataset;\n label.appendChild(dot);\n label.appendChild(textnode(updated));\n t.appendChild(label);\n container.appendChild(t);\n\n if (is_upload) {\n const menu = Menu.menu();\n t.appendChild(menu.container);\n Menu.add_menu_item(menu, \"Delete\", function () {\n const message = \"This will permanently delete the table \" + table.id + \".\";\n const confirm = \"To confirm type the name of the table below\";\n Overlay.deleteConfirmByTypingOverlay(\"Delete Table\", message, confirm, table.id, function () {\n Overlay.disableDismissal();\n const path = \"/api/v1/bq_tables/\" + table.project_id + \"/\" + table.dataset_id + \"/\" + table.id;\n Ajax.delete(path, function () {\n if (App.table_sets[table.owner_id] !== undefined) {\n const filtered = [];\n for (const t of App.table_sets[table.owner_id]) {\n if (t.dataset_id === table.dataset_id && t.id === table.id) {\n continue;\n }\n filtered.push(t);\n }\n App.table_sets[table.owner_id] = filtered;\n }\n App.render();\n Overlay.enableDismissal();\n Overlay.close();\n }, function () {\n const button = document.querySelector(\"div.overlay-panel-footer a.button\");\n if (button) {\n button.classList.remove(\"working\");\n }\n Overlay.enableDismissal();\n })\n });\n });\n }\n\n t.onclick = function () {\n const d = div(\"data-preview\", \"loading\");\n const loading = Loading.overlay();\n d.appendChild(loading);\n const table_path = table.dataset_id + \".\" + table.id;\n let q_str = \"SELECT * FROM \" + table_path;\n if (table.columns && table.columns.length > 0) {\n q_str += \" ORDER BY \" + table.columns[0].name + \" ASC\";\n }\n q_str += \" LIMIT 100;\"\n const q: ApiBQQuery = {\n project_id: table.project_id,\n dataset_id: table.dataset_id,\n table_id: table.id,\n query: q_str\n }\n Ajax.post(\"/api/v1/bq_query\", function (data: ApiBQResponse) {\n const table = document.createElement(\"table\");\n const t_head = document.createElement(\"thead\");\n const t_head_row = document.createElement(\"tr\");\n t_head.appendChild(t_head_row);\n table.appendChild(t_head);\n\n const idx_th = document.createElement(\"th\");\n idx_th.classList.add(\"idx\");\n t_head_row.appendChild(idx_th);\n for (const s of data.schema) {\n const th = document.createElement(\"th\");\n th.innerText = s.name;\n t_head_row.appendChild(th);\n }\n let idx = 0;\n for (const row of data.rows) {\n const tr = document.createElement(\"tr\");\n const index_td = document.createElement(\"td\");\n index_td.classList.add(\"idx\");\n index_td.innerText = (idx + 1).toString();\n tr.appendChild(index_td);\n for (const col of row) {\n const td = document.createElement(\"td\");\n td.innerText = col;\n tr.appendChild(td);\n }\n table.appendChild(tr);\n idx++;\n }\n d.insertBefore(table, d.firstChild);\n d.classList.remove(\"loading\");\n }, q);\n\n const overlay = new Overlay(OverlayStyle.Viz, table.id, [d], \"\", function () {\n //\n });\n overlay.panel.classList.add(\"large\");\n }\n }\n }\n\n if (empty) {\n const empty = div(\"empty-list\");\n empty.innerHTML = \"No data\";\n container.appendChild(empty);\n }\n }\n\n static render_page_links(pages: ApiPage[], container: HTMLElement, click_cb: Function) {\n const cols_container = div(\"viz-link-columns\");\n container.appendChild(cols_container);\n const cols = [];\n const heights: number[] = [];\n\n const width = container.getBoundingClientRect().width;\n const size = 240;\n const padding = 30;\n const link_height = 170;\n\n let col_count = Math.floor((width + padding) / (size + padding));\n if (col_count <= 0) {\n col_count = 1;\n }\n\n for (let i = 0; i < col_count; i++) {\n const col = div(\"viz-link-col\");\n cols_container.appendChild(col);\n cols.push(col);\n heights.push(0);\n }\n\n function min_col_idx() {\n if (heights.length === 0) {\n return 0;\n }\n const min = heights.reduce(function (a, b) {\n return Math.min(a, b);\n });\n for (let i = 0; i < heights.length; i++) {\n if (heights[i] === min) {\n return i;\n }\n }\n return 0;\n }\n\n let empty = true;\n for (const page of pages) {\n empty = false;\n const viz_el = div(\"viz-link\");\n const img = div(\"viz-link-img\");\n img.style.backgroundImage = \"url(https://storage.googleapis.com/daytum-viz-thumbnails/\" + page.id + \".png?\" + page.version + \")\";\n const w = 240;\n const h = 190;\n img.style.width = w + \"px\";\n img.style.height = h + \"px\";\n img.onclick = function () {\n click_cb(page);\n }\n const title = div(\"viz-link-title\");\n title.innerText = page.title;\n const meta = div(\"meta\");\n const date = new Date(page.created_at);\n meta.innerText = timeAgoDateFormat(date);\n viz_el.appendChild(img);\n viz_el.appendChild(title);\n viz_el.appendChild(meta);\n\n const view = anchor(\"view-icon\");\n view.appendChild(VizSVG.open_icon());\n title.appendChild(view);\n\n view.href = \"/page/\" + page.id;\n view.onclick = function (e) {\n if (e.button === 0 && !e.ctrlKey && !e.metaKey) {\n e.preventDefault();\n window.open(view.href, \"_blank\");\n }\n }\n\n const menu = Menu.menu();\n title.appendChild(menu.container);\n Menu.add_menu_item(menu, \"Delete\", function () {\n const message = \"Are you sure you want to delete \" + page.title + \"?\";\n Overlay.deleteConfirmOverlay(\"Delete Page\", message, function () {\n Overlay.disableDismissal();\n const path = \"/api/v1/pages/\" + page.id;\n Ajax.delete(path, function () {\n if (App.page_sets[page.owner_id] !== undefined) {\n const filtered = [];\n for (const p of App.page_sets[page.owner_id]) {\n if (p.id === page.id) {\n continue;\n }\n filtered.push(p);\n }\n App.page_sets[page.owner_id] = filtered;\n }\n App.render();\n Overlay.enableDismissal();\n Overlay.close();\n }, function () {\n const button = document.querySelector(\"div.overlay-panel-footer a.button\");\n if (button) {\n button.classList.remove(\"working\");\n }\n Overlay.enableDismissal();\n });\n });\n });\n\n const min_idx = min_col_idx();\n heights[min_idx] += link_height;\n cols[min_idx].appendChild(viz_el);\n }\n if (empty) {\n const empty = div(\"empty-list\");\n empty.innerHTML = \"No pages\";\n container.appendChild(empty);\n }\n }\n\n static render_left_rail(container: HTMLElement) {\n container.innerHTML = \"\";\n\n const rename_team = function (team: ApiTeam) {\n Teams.editTeamOverlay(team);\n };\n\n const delete_team = function (team: ApiTeam) {\n Teams.deleteTeamOverlay(team);\n };\n\n const show_members = function (team: ApiTeam) {\n Teams.teamMembersOverlay(team);\n };\n\n const link = function (name: string, team?: ApiTeam, img_url?: string): HTMLElement {\n const d = div(\"team-link\");\n const img = div(\"img\");\n if (img_url !== undefined) {\n img.style.backgroundImage = \"url(\" + img_url + \")\";\n } else {\n img.innerHTML = name.toUpperCase().substring(0, 1);\n }\n const title = div(\"team-link-title\");\n title.innerHTML = name;\n\n if (team !== undefined) {\n const menu = Menu.menu();\n d.appendChild(menu.container);\n\n Menu.add_menu_item(menu, \"Members\", function () {\n show_members(team);\n });\n\n const is_admin = Teams.userIsAdmin(App.user, team);\n if (is_admin) {\n const hr = document.createElement(\"hr\");\n menu.options.appendChild(hr);\n Menu.add_menu_item(menu, \"Rename\", function () {\n rename_team(team);\n });\n Menu.add_menu_item(menu, \"Delete\", function () {\n delete_team(team);\n });\n }\n\n }\n d.appendChild(img);\n d.appendChild(title);\n return d;\n };\n\n let private_img_url: string | undefined = undefined;\n if (App.user && App.user.image_timestamp !== null) {\n // TODO\n //private_img_url = VizApp.user.uploaded_avatar;\n }\n const private_link = link(\"Private\", undefined, private_img_url);\n if (App.user && App.selected_owner_id === App.user.id) {\n private_link.classList.add(\"selected\");\n }\n container.appendChild(private_link);\n private_link.onclick = function () {\n const path = \"/\";\n history.pushState({}, \"\", path);\n App.router.match();\n };\n\n for (const team of App.teams) {\n const l = link(team.name, team);\n if (App.selected_owner_id === team.id) {\n l.classList.add(\"selected\");\n }\n container.appendChild(l);\n l.onclick = function () {\n const path = \"/team/\" + team.id;\n history.pushState({}, \"\", path);\n App.router.match();\n };\n }\n const new_link = div(\"team-link\", \"new-team-link\");\n const new_img = div(\"img\");\n new_img.innerHTML = \"+\";\n const new_title = div(\"team-link-title\");\n new_title.innerHTML = \"Add Team\";\n new_link.appendChild(new_img);\n new_link.appendChild(new_title);\n container.appendChild(new_link);\n new_link.onclick = function (e) {\n e.preventDefault();\n if (DropdownState.menu_focused === true) {\n return;\n }\n Teams.newTeamOverlay();\n };\n }\n\n static section_header(title: string, button_label: string): SectionHeader {\n const header = div(\"list-header\");\n const title_el = span(\"list-title\");\n title_el.innerText = title;\n header.appendChild(title_el);\n\n const add = div(\"button\");\n add.innerText = button_label;\n header.appendChild(add);\n\n return {\n button: add,\n container: header,\n }\n }\n\n static render_main(container: HTMLElement) {\n container.innerHTML = \"\";\n const d = div(\"viz-index\");\n\n const data = div(\"data-list\");\n const data_header = FilesPage.section_header(\"Data\", \"Add\");\n data.appendChild(data_header.container);\n data_header.button.appendChild(SVG.chevron(\"white\"));\n d.appendChild(data);\n\n const input = Upload.input(App.selected_owner_id);\n data_header.button.appendChild(input);\n const menu = Menu.menu()\n data_header.button.appendChild(menu.container);\n Menu.add_menu_item(menu, \"Import CSV\", function () {\n input.click();\n })\n Menu.add_menu_item(menu, \"Connect to BigQuery\", function () {\n Upload.show_key_upload_overlay();\n })\n Menu.add_menu_divider(menu);\n Menu.add_menu_item(menu, \"Edit Connections\", function () {\n Upload.show_refresh_overlay(App.selected_owner_id);\n })\n\n const viz_list = div(\"viz-list\");\n\n const page_header = FilesPage.section_header(\"Pages\", \"New\");\n viz_list.appendChild(page_header.container);\n const page_list = div(\"page-list\");\n viz_list.appendChild(page_list);\n\n page_header.button.onclick = function () {\n const req: ApiVizPageCreateRequest = {\n id: uuid(),\n owner_id: App.selected_owner_id,\n }\n Ajax.post(\"/api/v1/pages\", function (data: ApiPage[]) {\n App.build_page_sets(data);\n const path = \"/editor/\" + req.id;\n history.pushState({}, \"\", path);\n App.router.match();\n }, req);\n }\n\n FilesPage.render_data_links(data);\n d.appendChild(viz_list);\n container.appendChild(d);\n\n let pages: ApiPage[] = [];\n if (App.page_sets[App.selected_owner_id] !== undefined) {\n pages = App.page_sets[App.selected_owner_id];\n }\n FilesPage.render_page_links(pages, page_list, function (page: ApiPage) {\n const path = \"/editor/\" + page.id;\n history.pushState({}, \"\", path);\n App.router.match();\n });\n\n }\n\n static avatar_url(user: ApiUser): string {\n if (!user.image_timestamp) {\n return \"\";\n }\n const base = \"https://storage.googleapis.com/daytum-thumbnails/\";\n const version = new Date(user.image_timestamp).getTime();\n const url = base + user.id + \"-120x120.png?\" + version;\n return url;\n }\n\n static render_nav(nav: HTMLElement) {\n nav.innerHTML = \"\";\n if (!App.user) {\n return;\n }\n nav.appendChild(div(\"spacer\"));\n const avatar = div(\"user-avatar\");\n if (App.user.image_timestamp) {\n const url = FilesPage.avatar_url(App.user);\n avatar.style.backgroundImage = \"url(\" + url + \")\";\n }\n nav.appendChild(avatar);\n\n const menu = Menu.menu();\n Menu.add_menu_header(menu, App.user.name, App.user.email);\n Menu.add_menu_divider(menu);\n Menu.add_menu_item(menu, \"Settings\", function () {\n if (!App.user) {\n return;\n }\n const d = div();\n new Overlay(OverlayStyle.Viz, \"Settings\", [d], \"\", function () {\n //\n });\n Settings.render_profile_settings(App.user, d);\n });\n Menu.add_menu_divider(menu);\n Menu.add_menu_item(menu, \"Sign Out\", function () {\n Ajax.get(\"/api/v1/logout\", function () {\n window.location.href = \"/\";\n })\n });\n menu.options.classList.add(\"inset\");\n avatar.appendChild(menu.container);\n }\n\n}", "import { ApiPage, ApiBQTable } from \"./api_data\";\nimport { div } from \"../../shared/dom\";\nimport { Display } from \"./display\";\nimport { BQ } from \"./bq\";\nimport { App } from \"./app\";\nimport { Loading } from \"../../shared/loading\";\n\nexport interface VizConnection {\n id: string;\n viz: Display;\n position: number;\n group: string;\n}\n\nexport class Page {\n\n static page: Page | null = null;\n\n viz_list: VizConnection[] = [];\n\n id: string;\n owner_id: string;\n title: string;\n version: number;\n\n selected_element: string | null = null;\n data_panel_open = false;\n show_query: boolean = false;\n\n constructor(id: string, owner_id: string, title: string, version: number) {\n this.id = id;\n this.owner_id = owner_id;\n this.title = title;\n this.version = version;\n }\n\n static parse(api_page: ApiPage, tables: ApiBQTable[]): Page {\n const page = new Page(api_page.id, api_page.owner_id, api_page.title, api_page.version);\n for (const api_d of api_page.displays) {\n const d = Display.parse(api_d, tables);\n if (api_page.connections) {\n for (const conn of api_page.connections) {\n if (conn.key !== \"viz\" || conn.child !== d.id) {\n continue;\n }\n let group = \"left\";\n let position = 0;\n if (api_page.attributes) {\n for (const attr of api_page.attributes) {\n if (attr.parent !== conn.id) {\n continue;\n }\n if (attr.key === \"group\") {\n if (attr.text === \"right\") {\n group = \"right\";\n }\n } else if (attr.key === \"position\") {\n if (attr.number) {\n position = attr.number;\n }\n }\n }\n }\n const c: VizConnection = {\n id: conn.id,\n viz: d,\n position: position,\n group: group,\n }\n page.viz_list.push(c);\n }\n }\n }\n if (App.user && api_page.attributes) {\n for (const attr of api_page.attributes) {\n if (attr.parent !== App.user.id) {\n continue;\n }\n if (attr.key === \"selected_element\" && attr.text) {\n page.selected_element = attr.text;\n } else if (attr.key === \"data_panel_open\") {\n const b = attr.number === 1 ? true : false;\n page.data_panel_open = b;\n }\n }\n }\n\n page.viz_list.sort(function (a, b) {\n return a.position - b.position;\n });\n return page;\n }\n\n static render_viz(conn: VizConnection): HTMLElement {\n const d = div(\"display\", \"loading\");\n\n const content = div(\"content\");\n d.appendChild(content);\n\n const svg = document.createElementNS(\"http://www.w3.org/2000/svg\", \"svg\");\n svg.classList.add(\"display_00c0f3\");\n content.appendChild(svg);\n\n content.appendChild(Loading.overlay());\n Display.render(conn.viz, svg, 11);\n\n if (conn.viz.selected_table) {\n BQ.run(conn.viz.selected_table.table, conn.viz, function () {\n d.classList.remove(\"loading\");\n Display.render(conn.viz, svg, 11);\n }, function () {\n // error\n d.classList.remove(\"loading\");\n })\n } else {\n d.classList.remove(\"loading\");\n }\n return d;\n }\n\n static render_nav(container: HTMLElement) {\n container.innerHTML = \"\";\n if (!Page.page) {\n return;\n }\n const h1 = document.createElement(\"h1\");\n h1.innerText = Page.page.title;\n container.appendChild(h1);\n }\n\n static render_main(container: HTMLElement) {\n container.innerHTML = \"\";\n\n if (!Page.page) {\n return;\n }\n const page = Page.page;\n\n const wrap = div(\"wrapper\");\n container.appendChild(wrap);\n const cols = div(\"flex-col-container\");\n wrap.appendChild(cols);\n\n const render_col = function (viz_list: VizConnection[], group_key: string) {\n const col = div(\"col\");\n cols.appendChild(col);\n\n const set = div();\n col.appendChild(set);\n for (const v of viz_list) {\n if (v.group !== group_key) {\n continue;\n }\n const viz_el = Page.render_viz(v);\n set.appendChild(viz_el);\n }\n }\n\n render_col(page.viz_list, \"left\");\n cols.appendChild(div(\"col-spacer\"));\n render_col(page.viz_list, \"right\");\n }\n\n}", "import { div, anchor } from \"../../shared/dom\";\nimport { App } from \"./app\";\nimport { Auth } from \"./auth\";\n\nexport class IndexPage {\n\n static render_main(container: HTMLElement) {\n container.innerHTML = \"\";\n const d = div(\"viz-index\");\n container.appendChild(d);\n Auth.render_signup(container);\n }\n\n static render_nav(nav: HTMLElement) {\n nav.innerHTML = \"\";\n const login = anchor(\"nav-a\");\n login.innerText = \"Sign In\";\n login.href = \"/login\";\n nav.appendChild(div(\"spacer\"));\n nav.appendChild(login);\n App.enable_link(login);\n }\n}", "import { Ajax } from \"../../shared/ajax\";\nimport { ApiUserData, ApiTeam, ApiUser, ApiBQTable, ApiPage, ApiPageData } from \"./api_data\";\nimport { div, anchor, input } from \"../../shared/dom\";\nimport { Router } from '../../shared/router';\nimport { Editor } from \"./editor\";\nimport { EditorPage } from \"./editor_page\";\nimport { FilesPage } from \"./files_page\";\nimport { Page, VizConnection } from \"./page\";\nimport { Display } from \"./display\";\nimport { IndexPage } from \"./index_page\";\nimport { SVG } from \"../../shared/svg\";\nimport { Auth } from \"./auth\";\n\nexport interface PivotMeasure {\n id: string;\n column: string;\n}\n\nexport interface BQData {\n project_id: string;\n dataset_id: string;\n table_id: string;\n column_name: string;\n column_type: string;\n rows: any[];\n\n pivoted: boolean;\n pivot_facet: string | null; // day of week, etc for date pivots\n pivot: string | null; // pivot match, for ex. \"Monday\" for dates, or \"Ride\" for strings\n pivot_op: string | null; // Sum or null\n pivot_target: string | null; // target column for sum\n pivot_measures: PivotMeasure[]; // list of selected target columns\n\n operation: string | null;\n\n loading: boolean;\n hidden: boolean;\n closed: boolean;\n}\n\nenum View {\n Login,\n SignupActivate,\n Index,\n Files,\n Editor,\n Page,\n}\n\nexport class App {\n\n static view: View = View.Index;\n static router = new Router();\n static user: ApiUser | null = null;\n static teams: ApiTeam[] = [];\n static selected_owner_id: string = \"\";\n\n static tables: ApiBQTable[] = [];\n static table_sets: { [id: string]: ApiBQTable[] } = {};\n static page_sets: { [id: string]: ApiPage[] } = {};\n\n static selected_page: Page | null = null;\n\n static input_focused = false;\n static thumbnail_dirty_count = 0;\n static new_graph_data = false;\n static updating_count = 0;\n\n static translate_x = 0;\n static translate_y = 0;\n static zoom = 1;\n\n static navigate(href: string) {\n history.pushState({}, \"\", href);\n App.router.match();\n }\n\n static enable_link(a: HTMLAnchorElement) {\n a.onclick = function (e) {\n if (e.button === 0 && !e.ctrlKey && !e.metaKey) {\n e.preventDefault();\n App.navigate(a.href);\n }\n }\n }\n\n static build_table_sets(data: ApiBQTable[]) {\n App.table_sets = {};\n for (const t of data) {\n if (App.table_sets[t.owner_id] === undefined) {\n App.table_sets[t.owner_id] = [];\n }\n App.table_sets[t.owner_id].push(t);\n }\n }\n\n static build_page_sets(data: ApiPage[]) {\n App.page_sets = {};\n for (const p of data) {\n if (App.page_sets[p.owner_id] === undefined) {\n App.page_sets[p.owner_id] = [];\n }\n App.page_sets[p.owner_id].push(p);\n }\n }\n\n static input(...node_class: string[]): HTMLInputElement {\n const i = input(...node_class);\n i.addEventListener('focus', () => {\n App.input_focused = true;\n });\n i.addEventListener('blur', () => {\n App.input_focused = false;\n });\n return i;\n }\n\n static render(...args: string[]) {\n let header = document.querySelector(\"div.fixed-header\") as HTMLElement;\n if (!header) {\n header = div(\"fixed-header\");\n document.body.appendChild(header);\n const logo = div(\"logo\");\n const a = anchor();\n a.href = \"/\";\n a.appendChild(SVG.logo());\n logo.appendChild(a);\n header.appendChild(logo);\n }\n let nav = document.querySelector(\"div.nav\") as HTMLElement;\n if (!nav) {\n nav = div(\"nav\");\n header.appendChild(nav);\n }\n let left = document.querySelector(\"div.left\") as HTMLElement;\n if (!left) {\n left = div(\"left\");\n document.body.appendChild(left);\n }\n let main = document.querySelector(\"div.main\") as HTMLElement;\n if (!main) {\n main = div(\"main\");\n document.body.appendChild(main);\n }\n\n // left rail gets replaced on each render\n left.innerHTML = \"\";\n\n let index = document.querySelector(\"div.index\") as HTMLElement;\n if (!index) {\n index = div(\"index\");\n document.body.appendChild(index);\n }\n\n let files = document.querySelector(\"div.viz-files\") as HTMLElement;\n if (!files) {\n files = div(\"viz-files\");\n main.appendChild(files);\n }\n\n let editor = document.querySelector(\"div.editor\") as HTMLElement;\n if (!editor) {\n editor = div(\"editor\");\n main.appendChild(editor);\n }\n\n header.style.display = \"none\";\n left.style.display = \"none\";\n main.style.display = \"none\";\n index.style.display = \"none\";\n files.style.display = \"none\";\n editor.style.display = \"none\";\n\n switch (App.view) {\n case View.Login:\n index.style.display = \"block\";\n Auth.render_login(index);\n break;\n\n case View.SignupActivate:\n index.style.display = \"block\";\n const token = args.length > 0 ? args[0] : \"\";\n Auth.render_activate(index, token);\n break;\n\n case View.Index:\n header.style.display = \"flex\";\n index.style.display = \"block\";\n IndexPage.render_main(index);\n IndexPage.render_nav(nav);\n break;\n\n case View.Files:\n header.style.display = \"flex\";\n left.style.display = \"block\";\n main.style.display = \"block\";\n files.style.display = \"block\";\n FilesPage.render_left_rail(left);\n FilesPage.render_main(files);\n FilesPage.render_nav(nav);\n break;\n\n case View.Page:\n header.style.display = \"flex\";\n index.style.display = \"block\";\n Page.render_main(index);\n Page.render_nav(nav);\n break;\n\n default:\n header.style.display = \"flex\";\n left.style.display = \"block\";\n main.style.display = \"block\";\n editor.style.display = \"block\";\n EditorPage.render_left_rail(left);\n EditorPage.render_main(editor);\n EditorPage.render_nav(nav);\n break;\n }\n\n if (App.selected_page) {\n const run = function (v: VizConnection) {\n Display.build_query_columns(v.viz);\n if (v.viz.data_changes) {\n Editor.run(v.viz);\n v.viz.data_changes = false;\n }\n }\n for (const v of App.selected_page.viz_list) {\n run(v);\n }\n }\n }\n\n static get_user_data(cb: Function) {\n Ajax.get(\"/api/v1/user_data\", function (data: ApiUserData) {\n console.log(data);\n App.user = data.user;\n App.teams = data.teams;\n App.tables = data.tables;\n App.build_table_sets(data.tables);\n App.build_page_sets(data.pages);\n cb();\n }, function (status: number, _data: any) {\n if (status === 401) {\n console.log(\"no user\");\n }\n cb();\n })\n }\n\n static load_files(team_id?: string) {\n const cb = function () {\n if (!App.user) {\n App.view = View.Index;\n App.render();\n return;\n }\n let id = \"\";\n if (team_id !== undefined && team_id !== \"\") {\n id = team_id;\n } else if (App.user) {\n id = App.user.id;\n }\n App.selected_owner_id = id;\n App.view = View.Files;\n App.render();\n }\n\n App.get_user_data(function () {\n cb();\n });\n }\n\n static load_editor(page_id?: string) {\n const cb = function () {\n if (!App.user) {\n App.view = View.Index;\n App.render();\n return;\n }\n let owner_id = \"\";\n for (const k in App.page_sets) {\n if (App.page_sets.hasOwnProperty(k)) {\n const set = App.page_sets[k];\n for (const api_page of set) {\n if (api_page.id === page_id) {\n const page = Page.parse(api_page, App.tables);\n App.selected_page = page;\n owner_id = page.owner_id;\n break;\n }\n }\n }\n }\n\n if (App.user && owner_id === \"\") {\n owner_id = App.user.id;\n }\n App.selected_owner_id = owner_id;\n App.view = View.Editor;\n App.render();\n Editor.zoom_to_fit();\n Editor.run();\n\n if (App.user && App.selected_owner_id !== App.user.id) {\n const home_link = document.querySelector(\"div.logo a\") as HTMLLinkElement;\n if (home_link) {\n home_link.href = \"/team/\" + App.selected_owner_id;\n }\n }\n }\n\n App.get_user_data(function () {\n cb();\n });\n }\n\n static load_login() {\n App.view = View.Login;\n App.render();\n }\n\n static load_signup(token?: string) {\n if (token !== undefined) {\n App.view = View.SignupActivate;\n App.render(token);\n return;\n }\n App.render();\n }\n\n static load_page(page_id?: string) {\n const cb = function () {\n App.view = View.Page;\n App.render();\n }\n\n Ajax.get(\"/api/v1/pages/\" + page_id, function (data: ApiPageData) {\n if (data.page) {\n const page = Page.parse(data.page, data.tables);\n Page.page = page;\n }\n if (data.user) {\n App.user = data.user;\n }\n cb();\n }, function (_status: number, _data: any) {\n cb();\n })\n }\n\n static start() {\n App.router.add(\"/\", App.load_files);\n App.router.add(\"/team/:team_id\", App.load_files);\n App.router.add(\"/editor/:page_id\", App.load_editor);\n App.router.add(\"/login\", App.load_login);\n App.router.add(\"/signup/:token\", App.load_signup);\n App.router.add(\"/page/:page_id\", App.load_page);\n App.router.add_not_found_route(App.load_files);\n\n window.addEventListener('popstate', function () {\n App.router.match();\n });\n\n App.router.match();\n console.log(\"git: __GIT_REV__\");\n }\n}\n\nwindow.addEventListener(\"load\", function () {\n App.start();\n\n document.addEventListener(\"keydown\", function (e) {\n if (e.keyCode === 8 || e.keyCode === 46) { // delete\n Editor.delete_selected_viz();\n } else if (e.keyCode === 187) { // +\n if (e.ctrlKey || e.metaKey) {\n e.preventDefault();\n }\n Editor.zoom_in();\n } else if (e.keyCode === 189) { // -\n if (e.ctrlKey || e.metaKey) {\n e.preventDefault();\n }\n Editor.zoom_out();\n } else if (e.keyCode === 48) { // 0\n Editor.zoom_reset();\n } else if (e.keyCode === 49) { // 1\n Editor.zoom_to_fit();\n }\n })\n})\n\nwindow.addEventListener(\"resize\", function () {\n if (App.view === View.Index) {\n App.render();\n }\n\n EditorPage.set_transform_origin();\n});", "// Unique ID creation requires a high quality random # generator. In the\n// browser this is a little complicated due to unknown quality of Math.random()\n// and inconsistent support for the `crypto` API. We do the best we can via\n// feature-detection\n\n// getRandomValues needs to be invoked in a context where \"this\" is a Crypto\n// implementation. Also, find the complete implementation of crypto on IE11.\nvar getRandomValues = (typeof(crypto) != 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto)) ||\n (typeof(msCrypto) != 'undefined' && typeof window.msCrypto.getRandomValues == 'function' && msCrypto.getRandomValues.bind(msCrypto));\n\nif (getRandomValues) {\n // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto\n var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef\n\n module.exports = function whatwgRNG() {\n getRandomValues(rnds8);\n return rnds8;\n };\n} else {\n // Math.random()-based (RNG)\n //\n // If all else fails, use Math.random(). It's fast, but is of unspecified\n // quality.\n var rnds = new Array(16);\n\n module.exports = function mathRNG() {\n for (var i = 0, r; i < 16; i++) {\n if ((i & 0x03) === 0) r = Math.random() * 0x100000000;\n rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;\n }\n\n return rnds;\n };\n}\n", "/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nvar byteToHex = [];\nfor (var i = 0; i < 256; ++i) {\n byteToHex[i] = (i + 0x100).toString(16).substr(1);\n}\n\nfunction bytesToUuid(buf, offset) {\n var i = offset || 0;\n var bth = byteToHex;\n // join used to fix memory issue caused by concatenation: https://bugs.chromium.org/p/v8/issues/detail?id=3175#c4\n return ([\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]], '-',\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]],\n bth[buf[i++]], bth[buf[i++]]\n ]).join('');\n}\n\nmodule.exports = bytesToUuid;\n", "var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\n\nvar _nodeId;\nvar _clockseq;\n\n// Previous uuid creation time\nvar _lastMSecs = 0;\nvar _lastNSecs = 0;\n\n// See https://github.com/uuidjs/uuid for API details\nfunction v1(options, buf, offset) {\n var i = buf && offset || 0;\n var b = buf || [];\n\n options = options || {};\n var node = options.node || _nodeId;\n var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;\n\n // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n if (node == null || clockseq == null) {\n var seedBytes = rng();\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [\n seedBytes[0] | 0x01,\n seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]\n ];\n }\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n }\n\n // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();\n\n // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;\n\n // Time since last uuid creation (in msecs)\n var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;\n\n // Per 4.2.1.2, Bump clockseq on clock regression\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n }\n\n // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n }\n\n // Per 4.2.1.2 Throw error if too many uuids are requested\n if (nsecs >= 10000) {\n throw new Error('uuid.v1(): Can\\'t create more than 10M uuids/sec');\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq;\n\n // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n msecs += 12219292800000;\n\n // `time_low`\n var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff;\n\n // `time_mid`\n var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff;\n\n // `time_high_and_version`\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n b[i++] = tmh >>> 16 & 0xff;\n\n // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n b[i++] = clockseq >>> 8 | 0x80;\n\n // `clock_seq_low`\n b[i++] = clockseq & 0xff;\n\n // `node`\n for (var n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf ? buf : bytesToUuid(b);\n}\n\nmodule.exports = v1;\n", "var rng = require('./lib/rng');\nvar bytesToUuid = require('./lib/bytesToUuid');\n\nfunction v4(options, buf, offset) {\n var i = buf && offset || 0;\n\n if (typeof(options) == 'string') {\n buf = options === 'binary' ? new Array(16) : null;\n options = null;\n }\n options = options || {};\n\n var rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = (rnds[6] & 0x0f) | 0x40;\n rnds[8] = (rnds[8] & 0x3f) | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n for (var ii = 0; ii < 16; ++ii) {\n buf[i + ii] = rnds[ii];\n }\n }\n\n return buf || bytesToUuid(rnds);\n}\n\nmodule.exports = v4;\n", "var v1 = require('./v1');\nvar v4 = require('./v4');\n\nvar uuid = v4;\nuuid.v1 = v1;\nuuid.v4 = v4;\n\nmodule.exports = uuid;\n", "/**\n * @license\n * Lodash \n * Copyright OpenJS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\n;(function() {\n\n /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n var undefined;\n\n /** Used as the semantic version number. */\n var VERSION = '4.17.20';\n\n /** Used as the size to enable large array optimizations. */\n var LARGE_ARRAY_SIZE = 200;\n\n /** Error message constants. */\n var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',\n FUNC_ERROR_TEXT = 'Expected a function';\n\n /** Used to stand-in for `undefined` hash values. */\n var HASH_UNDEFINED = '__lodash_hash_undefined__';\n\n /** Used as the maximum memoize cache size. */\n var MAX_MEMOIZE_SIZE = 500;\n\n /** Used as the internal argument placeholder. */\n var PLACEHOLDER = '__lodash_placeholder__';\n\n /** Used to compose bitmasks for cloning. */\n var CLONE_DEEP_FLAG = 1,\n CLONE_FLAT_FLAG = 2,\n CLONE_SYMBOLS_FLAG = 4;\n\n /** Used to compose bitmasks for value comparisons. */\n var COMPARE_PARTIAL_FLAG = 1,\n COMPARE_UNORDERED_FLAG = 2;\n\n /** Used to compose bitmasks for function metadata. */\n var WRAP_BIND_FLAG = 1,\n WRAP_BIND_KEY_FLAG = 2,\n WRAP_CURRY_BOUND_FLAG = 4,\n WRAP_CURRY_FLAG = 8,\n WRAP_CURRY_RIGHT_FLAG = 16,\n WRAP_PARTIAL_FLAG = 32,\n WRAP_PARTIAL_RIGHT_FLAG = 64,\n WRAP_ARY_FLAG = 128,\n WRAP_REARG_FLAG = 256,\n WRAP_FLIP_FLAG = 512;\n\n /** Used as default options for `_.truncate`. */\n var DEFAULT_TRUNC_LENGTH = 30,\n DEFAULT_TRUNC_OMISSION = '...';\n\n /** Used to detect hot functions by number of calls within a span of milliseconds. */\n var HOT_COUNT = 800,\n HOT_SPAN = 16;\n\n /** Used to indicate the type of lazy iteratees. */\n var LAZY_FILTER_FLAG = 1,\n LAZY_MAP_FLAG = 2,\n LAZY_WHILE_FLAG = 3;\n\n /** Used as references for various `Number` constants. */\n var INFINITY = 1 / 0,\n MAX_SAFE_INTEGER = 9007199254740991,\n MAX_INTEGER = 1.7976931348623157e+308,\n NAN = 0 / 0;\n\n /** Used as references for the maximum length and index of an array. */\n var MAX_ARRAY_LENGTH = 4294967295,\n MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n /** Used to associate wrap methods with their bit flags. */\n var wrapFlags = [\n ['ary', WRAP_ARY_FLAG],\n ['bind', WRAP_BIND_FLAG],\n ['bindKey', WRAP_BIND_KEY_FLAG],\n ['curry', WRAP_CURRY_FLAG],\n ['curryRight', WRAP_CURRY_RIGHT_FLAG],\n ['flip', WRAP_FLIP_FLAG],\n ['partial', WRAP_PARTIAL_FLAG],\n ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],\n ['rearg', WRAP_REARG_FLAG]\n ];\n\n /** `Object#toString` result references. */\n var argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n asyncTag = '[object AsyncFunction]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n domExcTag = '[object DOMException]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n genTag = '[object GeneratorFunction]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n nullTag = '[object Null]',\n objectTag = '[object Object]',\n promiseTag = '[object Promise]',\n proxyTag = '[object Proxy]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n symbolTag = '[object Symbol]',\n undefinedTag = '[object Undefined]',\n weakMapTag = '[object WeakMap]',\n weakSetTag = '[object WeakSet]';\n\n var arrayBufferTag = '[object ArrayBuffer]',\n dataViewTag = '[object DataView]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n /** Used to match empty string literals in compiled template source. */\n var reEmptyStringLeading = /\\b__p \\+= '';/g,\n reEmptyStringMiddle = /\\b(__p \\+=) '' \\+/g,\n reEmptyStringTrailing = /(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g;\n\n /** Used to match HTML entities and HTML characters. */\n var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,\n reUnescapedHtml = /[&<>\"']/g,\n reHasEscapedHtml = RegExp(reEscapedHtml.source),\n reHasUnescapedHtml = RegExp(reUnescapedHtml.source);\n\n /** Used to match template delimiters. */\n var reEscape = /<%-([\\s\\S]+?)%>/g,\n reEvaluate = /<%([\\s\\S]+?)%>/g,\n reInterpolate = /<%=([\\s\\S]+?)%>/g;\n\n /** Used to match property names within property paths. */\n var reIsDeepProp = /\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,\n reIsPlainProp = /^\\w*$/,\n rePropName = /[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g;\n\n /**\n * Used to match `RegExp`\n * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).\n */\n var reRegExpChar = /[\\\\^$.*+?()[\\]{}|]/g,\n reHasRegExpChar = RegExp(reRegExpChar.source);\n\n /** Used to match leading and trailing whitespace. */\n var reTrim = /^\\s+|\\s+$/g,\n reTrimStart = /^\\s+/,\n reTrimEnd = /\\s+$/;\n\n /** Used to match wrap detail comments. */\n var reWrapComment = /\\{(?:\\n\\/\\* \\[wrapped with .+\\] \\*\\/)?\\n?/,\n reWrapDetails = /\\{\\n\\/\\* \\[wrapped with (.+)\\] \\*/,\n reSplitDetails = /,? & /;\n\n /** Used to match words composed of alphanumeric characters. */\n var reAsciiWord = /[^\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\x7f]+/g;\n\n /** Used to match backslashes in property paths. */\n var reEscapeChar = /\\\\(\\\\)?/g;\n\n /**\n * Used to match\n * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).\n */\n var reEsTemplate = /\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g;\n\n /** Used to match `RegExp` flags from their coerced string values. */\n var reFlags = /\\w*$/;\n\n /** Used to detect bad signed hexadecimal string values. */\n var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;\n\n /** Used to detect binary string values. */\n var reIsBinary = /^0b[01]+$/i;\n\n /** Used to detect host constructors (Safari). */\n var reIsHostCtor = /^\\[object .+?Constructor\\]$/;\n\n /** Used to detect octal string values. */\n var reIsOctal = /^0o[0-7]+$/i;\n\n /** Used to detect unsigned integer values. */\n var reIsUint = /^(?:0|[1-9]\\d*)$/;\n\n /** Used to match Latin Unicode letters (excluding mathematical operators). */\n var reLatin = /[\\xc0-\\xd6\\xd8-\\xf6\\xf8-\\xff\\u0100-\\u017f]/g;\n\n /** Used to ensure capturing order of template delimiters. */\n var reNoMatch = /($^)/;\n\n /** Used to match unescaped characters in compiled string literals. */\n var reUnescapedString = /['\\n\\r\\u2028\\u2029\\\\]/g;\n\n /** Used to compose unicode character classes. */\n var rsAstralRange = '\\\\ud800-\\\\udfff',\n rsComboMarksRange = '\\\\u0300-\\\\u036f',\n reComboHalfMarksRange = '\\\\ufe20-\\\\ufe2f',\n rsComboSymbolsRange = '\\\\u20d0-\\\\u20ff',\n rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,\n rsDingbatRange = '\\\\u2700-\\\\u27bf',\n rsLowerRange = 'a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff',\n rsMathOpRange = '\\\\xac\\\\xb1\\\\xd7\\\\xf7',\n rsNonCharRange = '\\\\x00-\\\\x2f\\\\x3a-\\\\x40\\\\x5b-\\\\x60\\\\x7b-\\\\xbf',\n rsPunctuationRange = '\\\\u2000-\\\\u206f',\n rsSpaceRange = ' \\\\t\\\\x0b\\\\f\\\\xa0\\\\ufeff\\\\n\\\\r\\\\u2028\\\\u2029\\\\u1680\\\\u180e\\\\u2000\\\\u2001\\\\u2002\\\\u2003\\\\u2004\\\\u2005\\\\u2006\\\\u2007\\\\u2008\\\\u2009\\\\u200a\\\\u202f\\\\u205f\\\\u3000',\n rsUpperRange = 'A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde',\n rsVarRange = '\\\\ufe0e\\\\ufe0f',\n rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;\n\n /** Used to compose unicode capture groups. */\n var rsApos = \"['\\u2019]\",\n rsAstral = '[' + rsAstralRange + ']',\n rsBreak = '[' + rsBreakRange + ']',\n rsCombo = '[' + rsComboRange + ']',\n rsDigits = '\\\\d+',\n rsDingbat = '[' + rsDingbatRange + ']',\n rsLower = '[' + rsLowerRange + ']',\n rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',\n rsFitz = '\\\\ud83c[\\\\udffb-\\\\udfff]',\n rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',\n rsNonAstral = '[^' + rsAstralRange + ']',\n rsRegional = '(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}',\n rsSurrPair = '[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]',\n rsUpper = '[' + rsUpperRange + ']',\n rsZWJ = '\\\\u200d';\n\n /** Used to compose unicode regexes. */\n var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',\n rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',\n rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',\n rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',\n reOptMod = rsModifier + '?',\n rsOptVar = '[' + rsVarRange + ']?',\n rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',\n rsOrdLower = '\\\\d*(?:1st|2nd|3rd|(?![123])\\\\dth)(?=\\\\b|[A-Z_])',\n rsOrdUpper = '\\\\d*(?:1ST|2ND|3RD|(?![123])\\\\dTH)(?=\\\\b|[a-z_])',\n rsSeq = rsOptVar + reOptMod + rsOptJoin,\n rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,\n rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';\n\n /** Used to match apostrophes. */\n var reApos = RegExp(rsApos, 'g');\n\n /**\n * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and\n * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).\n */\n var reComboMark = RegExp(rsCombo, 'g');\n\n /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */\n var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');\n\n /** Used to match complex or compound words. */\n var reUnicodeWord = RegExp([\n rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',\n rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',\n rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,\n rsUpper + '+' + rsOptContrUpper,\n rsOrdUpper,\n rsOrdLower,\n rsDigits,\n rsEmoji\n ].join('|'), 'g');\n\n /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */\n var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');\n\n /** Used to detect strings that need a more robust regexp to match words. */\n var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;\n\n /** Used to assign default `context` object properties. */\n var contextProps = [\n 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',\n 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',\n 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',\n 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',\n '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'\n ];\n\n /** Used to make template sourceURLs easier to identify. */\n var templateCounter = -1;\n\n /** Used to identify `toStringTag` values of typed arrays. */\n var typedArrayTags = {};\n typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n typedArrayTags[uint32Tag] = true;\n typedArrayTags[argsTag] = typedArrayTags[arrayTag] =\n typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =\n typedArrayTags[errorTag] = typedArrayTags[funcTag] =\n typedArrayTags[mapTag] = typedArrayTags[numberTag] =\n typedArrayTags[objectTag] = typedArrayTags[regexpTag] =\n typedArrayTags[setTag] = typedArrayTags[stringTag] =\n typedArrayTags[weakMapTag] = false;\n\n /** Used to identify `toStringTag` values supported by `_.clone`. */\n var cloneableTags = {};\n cloneableTags[argsTag] = cloneableTags[arrayTag] =\n cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =\n cloneableTags[boolTag] = cloneableTags[dateTag] =\n cloneableTags[float32Tag] = cloneableTags[float64Tag] =\n cloneableTags[int8Tag] = cloneableTags[int16Tag] =\n cloneableTags[int32Tag] = cloneableTags[mapTag] =\n cloneableTags[numberTag] = cloneableTags[objectTag] =\n cloneableTags[regexpTag] = cloneableTags[setTag] =\n cloneableTags[stringTag] = cloneableTags[symbolTag] =\n cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\n cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\n cloneableTags[errorTag] = cloneableTags[funcTag] =\n cloneableTags[weakMapTag] = false;\n\n /** Used to map Latin Unicode letters to basic Latin letters. */\n var deburredLetters = {\n // Latin-1 Supplement block.\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcc': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xec': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss',\n // Latin Extended-A block.\n '\\u0100': 'A', '\\u0102': 'A', '\\u0104': 'A',\n '\\u0101': 'a', '\\u0103': 'a', '\\u0105': 'a',\n '\\u0106': 'C', '\\u0108': 'C', '\\u010a': 'C', '\\u010c': 'C',\n '\\u0107': 'c', '\\u0109': 'c', '\\u010b': 'c', '\\u010d': 'c',\n '\\u010e': 'D', '\\u0110': 'D', '\\u010f': 'd', '\\u0111': 'd',\n '\\u0112': 'E', '\\u0114': 'E', '\\u0116': 'E', '\\u0118': 'E', '\\u011a': 'E',\n '\\u0113': 'e', '\\u0115': 'e', '\\u0117': 'e', '\\u0119': 'e', '\\u011b': 'e',\n '\\u011c': 'G', '\\u011e': 'G', '\\u0120': 'G', '\\u0122': 'G',\n '\\u011d': 'g', '\\u011f': 'g', '\\u0121': 'g', '\\u0123': 'g',\n '\\u0124': 'H', '\\u0126': 'H', '\\u0125': 'h', '\\u0127': 'h',\n '\\u0128': 'I', '\\u012a': 'I', '\\u012c': 'I', '\\u012e': 'I', '\\u0130': 'I',\n '\\u0129': 'i', '\\u012b': 'i', '\\u012d': 'i', '\\u012f': 'i', '\\u0131': 'i',\n '\\u0134': 'J', '\\u0135': 'j',\n '\\u0136': 'K', '\\u0137': 'k', '\\u0138': 'k',\n '\\u0139': 'L', '\\u013b': 'L', '\\u013d': 'L', '\\u013f': 'L', '\\u0141': 'L',\n '\\u013a': 'l', '\\u013c': 'l', '\\u013e': 'l', '\\u0140': 'l', '\\u0142': 'l',\n '\\u0143': 'N', '\\u0145': 'N', '\\u0147': 'N', '\\u014a': 'N',\n '\\u0144': 'n', '\\u0146': 'n', '\\u0148': 'n', '\\u014b': 'n',\n '\\u014c': 'O', '\\u014e': 'O', '\\u0150': 'O',\n '\\u014d': 'o', '\\u014f': 'o', '\\u0151': 'o',\n '\\u0154': 'R', '\\u0156': 'R', '\\u0158': 'R',\n '\\u0155': 'r', '\\u0157': 'r', '\\u0159': 'r',\n '\\u015a': 'S', '\\u015c': 'S', '\\u015e': 'S', '\\u0160': 'S',\n '\\u015b': 's', '\\u015d': 's', '\\u015f': 's', '\\u0161': 's',\n '\\u0162': 'T', '\\u0164': 'T', '\\u0166': 'T',\n '\\u0163': 't', '\\u0165': 't', '\\u0167': 't',\n '\\u0168': 'U', '\\u016a': 'U', '\\u016c': 'U', '\\u016e': 'U', '\\u0170': 'U', '\\u0172': 'U',\n '\\u0169': 'u', '\\u016b': 'u', '\\u016d': 'u', '\\u016f': 'u', '\\u0171': 'u', '\\u0173': 'u',\n '\\u0174': 'W', '\\u0175': 'w',\n '\\u0176': 'Y', '\\u0177': 'y', '\\u0178': 'Y',\n '\\u0179': 'Z', '\\u017b': 'Z', '\\u017d': 'Z',\n '\\u017a': 'z', '\\u017c': 'z', '\\u017e': 'z',\n '\\u0132': 'IJ', '\\u0133': 'ij',\n '\\u0152': 'Oe', '\\u0153': 'oe',\n '\\u0149': \"'n\", '\\u017f': 's'\n };\n\n /** Used to map characters to HTML entities. */\n var htmlEscapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": '''\n };\n\n /** Used to map HTML entities to characters. */\n var htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\"\n };\n\n /** Used to escape characters for inclusion in compiled string literals. */\n var stringEscapes = {\n '\\\\': '\\\\',\n \"'\": \"'\",\n '\\n': 'n',\n '\\r': 'r',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n /** Built-in method references without a dependency on `root`. */\n var freeParseFloat = parseFloat,\n freeParseInt = parseInt;\n\n /** Detect free variable `global` from Node.js. */\n var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;\n\n /** Detect free variable `self`. */\n var freeSelf = typeof self == 'object' && self && self.Object === Object && self;\n\n /** Used as a reference to the global object. */\n var root = freeGlobal || freeSelf || Function('return this')();\n\n /** Detect free variable `exports`. */\n var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;\n\n /** Detect free variable `module`. */\n var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;\n\n /** Detect the popular CommonJS extension `module.exports`. */\n var moduleExports = freeModule && freeModule.exports === freeExports;\n\n /** Detect free variable `process` from Node.js. */\n var freeProcess = moduleExports && freeGlobal.process;\n\n /** Used to access faster Node.js helpers. */\n var nodeUtil = (function() {\n try {\n // Use `util.types` for Node.js 10+.\n var types = freeModule && freeModule.require && freeModule.require('util').types;\n\n if (types) {\n return types;\n }\n\n // Legacy `process.binding('util')` for Node.js < 10.\n return freeProcess && freeProcess.binding && freeProcess.binding('util');\n } catch (e) {}\n }());\n\n /* Node.js helper references. */\n var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,\n nodeIsDate = nodeUtil && nodeUtil.isDate,\n nodeIsMap = nodeUtil && nodeUtil.isMap,\n nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,\n nodeIsSet = nodeUtil && nodeUtil.isSet,\n nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * A faster alternative to `Function#apply`, this function invokes `func`\n * with the `this` binding of `thisArg` and the arguments of `args`.\n *\n * @private\n * @param {Function} func The function to invoke.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} args The arguments to invoke `func` with.\n * @returns {*} Returns the result of `func`.\n */\n function apply(func, thisArg, args) {\n switch (args.length) {\n case 0: return func.call(thisArg);\n case 1: return func.call(thisArg, args[0]);\n case 2: return func.call(thisArg, args[0], args[1]);\n case 3: return func.call(thisArg, args[0], args[1], args[2]);\n }\n return func.apply(thisArg, args);\n }\n\n /**\n * A specialized version of `baseAggregator` for arrays.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function arrayAggregator(array, setter, iteratee, accumulator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n var value = array[index];\n setter(accumulator, value, iteratee(value), array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.forEach` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEach(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.forEachRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEachRight(array, iteratee) {\n var length = array == null ? 0 : array.length;\n\n while (length--) {\n if (iteratee(array[length], length, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.every` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\n function arrayEvery(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (!predicate(array[index], index, array)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * A specialized version of `_.filter` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function arrayFilter(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.includes` for arrays without support for\n * specifying an index to search from.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludes(array, value) {\n var length = array == null ? 0 : array.length;\n return !!length && baseIndexOf(array, value, 0) > -1;\n }\n\n /**\n * This function is like `arrayIncludes` except that it accepts a comparator.\n *\n * @private\n * @param {Array} [array] The array to inspect.\n * @param {*} target The value to search for.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {boolean} Returns `true` if `target` is found, else `false`.\n */\n function arrayIncludesWith(array, value, comparator) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (comparator(value, array[index])) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `_.map` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function arrayMap(array, iteratee) {\n var index = -1,\n length = array == null ? 0 : array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n }\n\n /**\n * Appends the elements of `values` to `array`.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to append.\n * @returns {Array} Returns `array`.\n */\n function arrayPush(array, values) {\n var index = -1,\n length = values.length,\n offset = array.length;\n\n while (++index < length) {\n array[offset + index] = values[index];\n }\n return array;\n }\n\n /**\n * A specialized version of `_.reduce` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the first element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduce(array, iteratee, accumulator, initAccum) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n if (initAccum && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.reduceRight` for arrays without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initAccum] Specify using the last element of `array` as\n * the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduceRight(array, iteratee, accumulator, initAccum) {\n var length = array == null ? 0 : array.length;\n if (initAccum && length) {\n accumulator = array[--length];\n }\n while (length--) {\n accumulator = iteratee(accumulator, array[length], length, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.some` for arrays without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} [array] The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function arraySome(array, predicate) {\n var index = -1,\n length = array == null ? 0 : array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Gets the size of an ASCII `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n var asciiSize = baseProperty('length');\n\n /**\n * Converts an ASCII `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function asciiToArray(string) {\n return string.split('');\n }\n\n /**\n * Splits an ASCII `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function asciiWords(string) {\n return string.match(reAsciiWord) || [];\n }\n\n /**\n * The base implementation of methods like `_.findKey` and `_.findLastKey`,\n * without support for iteratee shorthands, which iterates over `collection`\n * using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\n function baseFindKey(collection, predicate, eachFunc) {\n var result;\n eachFunc(collection, function(value, key, collection) {\n if (predicate(value, key, collection)) {\n result = key;\n return false;\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.findIndex` and `_.findLastIndex` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} predicate The function invoked per iteration.\n * @param {number} fromIndex The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseFindIndex(array, predicate, fromIndex, fromRight) {\n var length = array.length,\n index = fromIndex + (fromRight ? 1 : -1);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.indexOf` without `fromIndex` bounds checks.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOf(array, value, fromIndex) {\n return value === value\n ? strictIndexOf(array, value, fromIndex)\n : baseFindIndex(array, baseIsNaN, fromIndex);\n }\n\n /**\n * This function is like `baseIndexOf` except that it accepts a comparator.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @param {Function} comparator The comparator invoked per element.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOfWith(array, value, fromIndex, comparator) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (comparator(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.isNaN` without support for number objects.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n */\n function baseIsNaN(value) {\n return value !== value;\n }\n\n /**\n * The base implementation of `_.mean` and `_.meanBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the mean.\n */\n function baseMean(array, iteratee) {\n var length = array == null ? 0 : array.length;\n return length ? (baseSum(array, iteratee) / length) : NAN;\n }\n\n /**\n * The base implementation of `_.property` without support for deep paths.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function baseProperty(key) {\n return function(object) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.propertyOf` without support for deep paths.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyOf(object) {\n return function(key) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.reduce` and `_.reduceRight`, without support\n * for iteratee shorthands, which iterates over `collection` using `eachFunc`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initAccum Specify using the first or last element of\n * `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\n function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {\n eachFunc(collection, function(value, index, collection) {\n accumulator = initAccum\n ? (initAccum = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.sortBy` which uses `comparer` to define the\n * sort order of `array` and replaces criteria objects with their corresponding\n * values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\n function baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.sum` and `_.sumBy` without support for\n * iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {number} Returns the sum.\n */\n function baseSum(array, iteratee) {\n var result,\n index = -1,\n length = array.length;\n\n while (++index < length) {\n var current = iteratee(array[index]);\n if (current !== undefined) {\n result = result === undefined ? current : (result + current);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.times` without support for iteratee shorthands\n * or max array length checks.\n *\n * @private\n * @param {number} n The number of times to invoke `iteratee`.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the array of results.\n */\n function baseTimes(n, iteratee) {\n var index = -1,\n result = Array(n);\n\n while (++index < n) {\n result[index] = iteratee(index);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array\n * of key-value pairs for `object` corresponding to the property names of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the key-value pairs.\n */\n function baseToPairs(object, props) {\n return arrayMap(props, function(key) {\n return [key, object[key]];\n });\n }\n\n /**\n * The base implementation of `_.unary` without support for storing metadata.\n *\n * @private\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n */\n function baseUnary(func) {\n return function(value) {\n return func(value);\n };\n }\n\n /**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * of `props`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\n function baseValues(object, props) {\n return arrayMap(props, function(key) {\n return object[key];\n });\n }\n\n /**\n * Checks if a `cache` value for `key` exists.\n *\n * @private\n * @param {Object} cache The cache to query.\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function cacheHas(cache, key) {\n return cache.has(key);\n }\n\n /**\n * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the first unmatched string symbol.\n */\n function charsStartIndex(strSymbols, chrSymbols) {\n var index = -1,\n length = strSymbols.length;\n\n while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol\n * that is not found in the character symbols.\n *\n * @private\n * @param {Array} strSymbols The string symbols to inspect.\n * @param {Array} chrSymbols The character symbols to find.\n * @returns {number} Returns the index of the last unmatched string symbol.\n */\n function charsEndIndex(strSymbols, chrSymbols) {\n var index = strSymbols.length;\n\n while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}\n return index;\n }\n\n /**\n * Gets the number of `placeholder` occurrences in `array`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} placeholder The placeholder to search for.\n * @returns {number} Returns the placeholder count.\n */\n function countHolders(array, placeholder) {\n var length = array.length,\n result = 0;\n\n while (length--) {\n if (array[length] === placeholder) {\n ++result;\n }\n }\n return result;\n }\n\n /**\n * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A\n * letters to basic Latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\n var deburrLetter = basePropertyOf(deburredLetters);\n\n /**\n * Used by `_.escape` to convert characters to HTML entities.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n var escapeHtmlChar = basePropertyOf(htmlEscapes);\n\n /**\n * Used by `_.template` to escape characters for inclusion in compiled string literals.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n function escapeStringChar(chr) {\n return '\\\\' + stringEscapes[chr];\n }\n\n /**\n * Gets the value at `key` of `object`.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function getValue(object, key) {\n return object == null ? undefined : object[key];\n }\n\n /**\n * Checks if `string` contains Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a symbol is found, else `false`.\n */\n function hasUnicode(string) {\n return reHasUnicode.test(string);\n }\n\n /**\n * Checks if `string` contains a word composed of Unicode symbols.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {boolean} Returns `true` if a word is found, else `false`.\n */\n function hasUnicodeWord(string) {\n return reHasUnicodeWord.test(string);\n }\n\n /**\n * Converts `iterator` to an array.\n *\n * @private\n * @param {Object} iterator The iterator to convert.\n * @returns {Array} Returns the converted array.\n */\n function iteratorToArray(iterator) {\n var data,\n result = [];\n\n while (!(data = iterator.next()).done) {\n result.push(data.value);\n }\n return result;\n }\n\n /**\n * Converts `map` to its key-value pairs.\n *\n * @private\n * @param {Object} map The map to convert.\n * @returns {Array} Returns the key-value pairs.\n */\n function mapToArray(map) {\n var index = -1,\n result = Array(map.size);\n\n map.forEach(function(value, key) {\n result[++index] = [key, value];\n });\n return result;\n }\n\n /**\n * Creates a unary function that invokes `func` with its argument transformed.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {Function} transform The argument transform.\n * @returns {Function} Returns the new function.\n */\n function overArg(func, transform) {\n return function(arg) {\n return func(transform(arg));\n };\n }\n\n /**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\n function replaceHolders(array, placeholder) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value === placeholder || value === PLACEHOLDER) {\n array[index] = PLACEHOLDER;\n result[resIndex++] = index;\n }\n }\n return result;\n }\n\n /**\n * Converts `set` to an array of its values.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the values.\n */\n function setToArray(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = value;\n });\n return result;\n }\n\n /**\n * Converts `set` to its value-value pairs.\n *\n * @private\n * @param {Object} set The set to convert.\n * @returns {Array} Returns the value-value pairs.\n */\n function setToPairs(set) {\n var index = -1,\n result = Array(set.size);\n\n set.forEach(function(value) {\n result[++index] = [value, value];\n });\n return result;\n }\n\n /**\n * A specialized version of `_.indexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictIndexOf(array, value, fromIndex) {\n var index = fromIndex - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * A specialized version of `_.lastIndexOf` which performs strict equality\n * comparisons of values, i.e. `===`.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} fromIndex The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function strictLastIndexOf(array, value, fromIndex) {\n var index = fromIndex + 1;\n while (index--) {\n if (array[index] === value) {\n return index;\n }\n }\n return index;\n }\n\n /**\n * Gets the number of symbols in `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the string size.\n */\n function stringSize(string) {\n return hasUnicode(string)\n ? unicodeSize(string)\n : asciiSize(string);\n }\n\n /**\n * Converts `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function stringToArray(string) {\n return hasUnicode(string)\n ? unicodeToArray(string)\n : asciiToArray(string);\n }\n\n /**\n * Used by `_.unescape` to convert HTML entities to characters.\n *\n * @private\n * @param {string} chr The matched character to unescape.\n * @returns {string} Returns the unescaped character.\n */\n var unescapeHtmlChar = basePropertyOf(htmlUnescapes);\n\n /**\n * Gets the size of a Unicode `string`.\n *\n * @private\n * @param {string} string The string inspect.\n * @returns {number} Returns the string size.\n */\n function unicodeSize(string) {\n var result = reUnicode.lastIndex = 0;\n while (reUnicode.test(string)) {\n ++result;\n }\n return result;\n }\n\n /**\n * Converts a Unicode `string` to an array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the converted array.\n */\n function unicodeToArray(string) {\n return string.match(reUnicode) || [];\n }\n\n /**\n * Splits a Unicode `string` into an array of its words.\n *\n * @private\n * @param {string} The string to inspect.\n * @returns {Array} Returns the words of `string`.\n */\n function unicodeWords(string) {\n return string.match(reUnicodeWord) || [];\n }\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * Create a new pristine `lodash` function using the `context` object.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Util\n * @param {Object} [context=root] The context object.\n * @returns {Function} Returns a new `lodash` function.\n * @example\n *\n * _.mixin({ 'foo': _.constant('foo') });\n *\n * var lodash = _.runInContext();\n * lodash.mixin({ 'bar': lodash.constant('bar') });\n *\n * _.isFunction(_.foo);\n * // => true\n * _.isFunction(_.bar);\n * // => false\n *\n * lodash.isFunction(lodash.foo);\n * // => false\n * lodash.isFunction(lodash.bar);\n * // => true\n *\n * // Create a suped-up `defer` in Node.js.\n * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;\n */\n var runInContext = (function runInContext(context) {\n context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));\n\n /** Built-in constructor references. */\n var Array = context.Array,\n Date = context.Date,\n Error = context.Error,\n Function = context.Function,\n Math = context.Math,\n Object = context.Object,\n RegExp = context.RegExp,\n String = context.String,\n TypeError = context.TypeError;\n\n /** Used for built-in method references. */\n var arrayProto = Array.prototype,\n funcProto = Function.prototype,\n objectProto = Object.prototype;\n\n /** Used to detect overreaching core-js shims. */\n var coreJsData = context['__core-js_shared__'];\n\n /** Used to resolve the decompiled source of functions. */\n var funcToString = funcProto.toString;\n\n /** Used to check objects for own properties. */\n var hasOwnProperty = objectProto.hasOwnProperty;\n\n /** Used to generate unique IDs. */\n var idCounter = 0;\n\n /** Used to detect methods masquerading as native. */\n var maskSrcKey = (function() {\n var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');\n return uid ? ('Symbol(src)_1.' + uid) : '';\n }());\n\n /**\n * Used to resolve the\n * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)\n * of values.\n */\n var nativeObjectToString = objectProto.toString;\n\n /** Used to infer the `Object` constructor. */\n var objectCtorString = funcToString.call(Object);\n\n /** Used to restore the original `_` reference in `_.noConflict`. */\n var oldDash = root._;\n\n /** Used to detect if a method is native. */\n var reIsNative = RegExp('^' +\n funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\\\$&')\n .replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n );\n\n /** Built-in value references. */\n var Buffer = moduleExports ? context.Buffer : undefined,\n Symbol = context.Symbol,\n Uint8Array = context.Uint8Array,\n allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,\n getPrototype = overArg(Object.getPrototypeOf, Object),\n objectCreate = Object.create,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n splice = arrayProto.splice,\n spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,\n symIterator = Symbol ? Symbol.iterator : undefined,\n symToStringTag = Symbol ? Symbol.toStringTag : undefined;\n\n var defineProperty = (function() {\n try {\n var func = getNative(Object, 'defineProperty');\n func({}, '', {});\n return func;\n } catch (e) {}\n }());\n\n /** Mocked built-ins. */\n var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,\n ctxNow = Date && Date.now !== root.Date.now && Date.now,\n ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;\n\n /* Built-in method references for those with the same name as other `lodash` methods. */\n var nativeCeil = Math.ceil,\n nativeFloor = Math.floor,\n nativeGetSymbols = Object.getOwnPropertySymbols,\n nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,\n nativeIsFinite = context.isFinite,\n nativeJoin = arrayProto.join,\n nativeKeys = overArg(Object.keys, Object),\n nativeMax = Math.max,\n nativeMin = Math.min,\n nativeNow = Date.now,\n nativeParseInt = context.parseInt,\n nativeRandom = Math.random,\n nativeReverse = arrayProto.reverse;\n\n /* Built-in method references that are verified to be native. */\n var DataView = getNative(context, 'DataView'),\n Map = getNative(context, 'Map'),\n Promise = getNative(context, 'Promise'),\n Set = getNative(context, 'Set'),\n WeakMap = getNative(context, 'WeakMap'),\n nativeCreate = getNative(Object, 'create');\n\n /** Used to store function metadata. */\n var metaMap = WeakMap && new WeakMap;\n\n /** Used to lookup unminified function names. */\n var realNames = {};\n\n /** Used to detect maps, sets, and weakmaps. */\n var dataViewCtorString = toSource(DataView),\n mapCtorString = toSource(Map),\n promiseCtorString = toSource(Promise),\n setCtorString = toSource(Set),\n weakMapCtorString = toSource(WeakMap);\n\n /** Used to convert symbols to primitives and strings. */\n var symbolProto = Symbol ? Symbol.prototype : undefined,\n symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,\n symbolToString = symbolProto ? symbolProto.toString : undefined;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` object which wraps `value` to enable implicit method\n * chain sequences. Methods that operate on and return arrays, collections,\n * and functions can be chained together. Methods that retrieve a single value\n * or may return a primitive value will automatically end the chain sequence\n * and return the unwrapped value. Otherwise, the value must be unwrapped\n * with `_#value`.\n *\n * Explicit chain sequences, which must be unwrapped with `_#value`, may be\n * enabled using `_.chain`.\n *\n * The execution of chained methods is lazy, that is, it's deferred until\n * `_#value` is implicitly or explicitly called.\n *\n * Lazy evaluation allows several methods to support shortcut fusion.\n * Shortcut fusion is an optimization to merge iteratee calls; this avoids\n * the creation of intermediate arrays and can greatly reduce the number of\n * iteratee executions. Sections of a chain sequence qualify for shortcut\n * fusion if the section is applied to an array and iteratees accept only\n * one argument. The heuristic for whether a section qualifies for shortcut\n * fusion is subject to change.\n *\n * Chaining is supported in custom builds as long as the `_#value` method is\n * directly or indirectly included in the build.\n *\n * In addition to lodash methods, wrappers have `Array` and `String` methods.\n *\n * The wrapper `Array` methods are:\n * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`\n *\n * The wrapper `String` methods are:\n * `replace` and `split`\n *\n * The wrapper methods that support shortcut fusion are:\n * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,\n * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,\n * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`\n *\n * The chainable wrapper methods are:\n * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,\n * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,\n * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,\n * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,\n * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,\n * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,\n * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,\n * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,\n * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,\n * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,\n * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,\n * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,\n * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,\n * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,\n * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,\n * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,\n * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,\n * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,\n * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,\n * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,\n * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,\n * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,\n * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,\n * `zipObject`, `zipObjectDeep`, and `zipWith`\n *\n * The wrapper methods that are **not** chainable by default are:\n * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,\n * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,\n * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,\n * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,\n * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,\n * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,\n * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,\n * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,\n * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,\n * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,\n * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,\n * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,\n * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,\n * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,\n * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,\n * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,\n * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,\n * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,\n * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,\n * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,\n * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,\n * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,\n * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,\n * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,\n * `upperFirst`, `value`, and `words`\n *\n * @name _\n * @constructor\n * @category Seq\n * @param {*} value The value to wrap in a `lodash` instance.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2, 3]);\n *\n * // Returns an unwrapped value.\n * wrapped.reduce(_.add);\n * // => 6\n *\n * // Returns a wrapped value.\n * var squares = wrapped.map(square);\n *\n * _.isArray(squares);\n * // => false\n *\n * _.isArray(squares.value());\n * // => true\n */\n function lodash(value) {\n if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n if (value instanceof LodashWrapper) {\n return value;\n }\n if (hasOwnProperty.call(value, '__wrapped__')) {\n return wrapperClone(value);\n }\n }\n return new LodashWrapper(value);\n }\n\n /**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} proto The object to inherit from.\n * @returns {Object} Returns the new object.\n */\n var baseCreate = (function() {\n function object() {}\n return function(proto) {\n if (!isObject(proto)) {\n return {};\n }\n if (objectCreate) {\n return objectCreate(proto);\n }\n object.prototype = proto;\n var result = new object;\n object.prototype = undefined;\n return result;\n };\n }());\n\n /**\n * The function whose prototype chain sequence wrappers inherit from.\n *\n * @private\n */\n function baseLodash() {\n // No operation performed.\n }\n\n /**\n * The base constructor for creating `lodash` wrapper objects.\n *\n * @private\n * @param {*} value The value to wrap.\n * @param {boolean} [chainAll] Enable explicit method chain sequences.\n */\n function LodashWrapper(value, chainAll) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__chain__ = !!chainAll;\n this.__index__ = 0;\n this.__values__ = undefined;\n }\n\n /**\n * By default, the template delimiters used by lodash are like those in\n * embedded Ruby (ERB) as well as ES2015 template strings. Change the\n * following template settings to use alternative delimiters.\n *\n * @static\n * @memberOf _\n * @type {Object}\n */\n lodash.templateSettings = {\n\n /**\n * Used to detect `data` property values to be HTML-escaped.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'escape': reEscape,\n\n /**\n * Used to detect code to be evaluated.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'evaluate': reEvaluate,\n\n /**\n * Used to detect `data` property values to inject.\n *\n * @memberOf _.templateSettings\n * @type {RegExp}\n */\n 'interpolate': reInterpolate,\n\n /**\n * Used to reference the data object in the template text.\n *\n * @memberOf _.templateSettings\n * @type {string}\n */\n 'variable': '',\n\n /**\n * Used to import variables into the compiled template.\n *\n * @memberOf _.templateSettings\n * @type {Object}\n */\n 'imports': {\n\n /**\n * A reference to the `lodash` function.\n *\n * @memberOf _.templateSettings.imports\n * @type {Function}\n */\n '_': lodash\n }\n };\n\n // Ensure wrappers are instances of `baseLodash`.\n lodash.prototype = baseLodash.prototype;\n lodash.prototype.constructor = lodash;\n\n LodashWrapper.prototype = baseCreate(baseLodash.prototype);\n LodashWrapper.prototype.constructor = LodashWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n *\n * @private\n * @constructor\n * @param {*} value The value to wrap.\n */\n function LazyWrapper(value) {\n this.__wrapped__ = value;\n this.__actions__ = [];\n this.__dir__ = 1;\n this.__filtered__ = false;\n this.__iteratees__ = [];\n this.__takeCount__ = MAX_ARRAY_LENGTH;\n this.__views__ = [];\n }\n\n /**\n * Creates a clone of the lazy wrapper object.\n *\n * @private\n * @name clone\n * @memberOf LazyWrapper\n * @returns {Object} Returns the cloned `LazyWrapper` object.\n */\n function lazyClone() {\n var result = new LazyWrapper(this.__wrapped__);\n result.__actions__ = copyArray(this.__actions__);\n result.__dir__ = this.__dir__;\n result.__filtered__ = this.__filtered__;\n result.__iteratees__ = copyArray(this.__iteratees__);\n result.__takeCount__ = this.__takeCount__;\n result.__views__ = copyArray(this.__views__);\n return result;\n }\n\n /**\n * Reverses the direction of lazy iteration.\n *\n * @private\n * @name reverse\n * @memberOf LazyWrapper\n * @returns {Object} Returns the new reversed `LazyWrapper` object.\n */\n function lazyReverse() {\n if (this.__filtered__) {\n var result = new LazyWrapper(this);\n result.__dir__ = -1;\n result.__filtered__ = true;\n } else {\n result = this.clone();\n result.__dir__ *= -1;\n }\n return result;\n }\n\n /**\n * Extracts the unwrapped value from its lazy wrapper.\n *\n * @private\n * @name value\n * @memberOf LazyWrapper\n * @returns {*} Returns the unwrapped value.\n */\n function lazyValue() {\n var array = this.__wrapped__.value(),\n dir = this.__dir__,\n isArr = isArray(array),\n isRight = dir < 0,\n arrLength = isArr ? array.length : 0,\n view = getView(0, arrLength, this.__views__),\n start = view.start,\n end = view.end,\n length = end - start,\n index = isRight ? end : (start - 1),\n iteratees = this.__iteratees__,\n iterLength = iteratees.length,\n resIndex = 0,\n takeCount = nativeMin(length, this.__takeCount__);\n\n if (!isArr || (!isRight && arrLength == length && takeCount == length)) {\n return baseWrapperValue(array, this.__actions__);\n }\n var result = [];\n\n outer:\n while (length-- && resIndex < takeCount) {\n index += dir;\n\n var iterIndex = -1,\n value = array[index];\n\n while (++iterIndex < iterLength) {\n var data = iteratees[iterIndex],\n iteratee = data.iteratee,\n type = data.type,\n computed = iteratee(value);\n\n if (type == LAZY_MAP_FLAG) {\n value = computed;\n } else if (!computed) {\n if (type == LAZY_FILTER_FLAG) {\n continue outer;\n } else {\n break outer;\n }\n }\n }\n result[resIndex++] = value;\n }\n return result;\n }\n\n // Ensure `LazyWrapper` is an instance of `baseLodash`.\n LazyWrapper.prototype = baseCreate(baseLodash.prototype);\n LazyWrapper.prototype.constructor = LazyWrapper;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a hash object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Hash(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the hash.\n *\n * @private\n * @name clear\n * @memberOf Hash\n */\n function hashClear() {\n this.__data__ = nativeCreate ? nativeCreate(null) : {};\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the hash.\n *\n * @private\n * @name delete\n * @memberOf Hash\n * @param {Object} hash The hash to modify.\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function hashDelete(key) {\n var result = this.has(key) && delete this.__data__[key];\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the hash value for `key`.\n *\n * @private\n * @name get\n * @memberOf Hash\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function hashGet(key) {\n var data = this.__data__;\n if (nativeCreate) {\n var result = data[key];\n return result === HASH_UNDEFINED ? undefined : result;\n }\n return hasOwnProperty.call(data, key) ? data[key] : undefined;\n }\n\n /**\n * Checks if a hash value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Hash\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function hashHas(key) {\n var data = this.__data__;\n return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);\n }\n\n /**\n * Sets the hash `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Hash\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the hash instance.\n */\n function hashSet(key, value) {\n var data = this.__data__;\n this.size += this.has(key) ? 0 : 1;\n data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;\n return this;\n }\n\n // Add methods to `Hash`.\n Hash.prototype.clear = hashClear;\n Hash.prototype['delete'] = hashDelete;\n Hash.prototype.get = hashGet;\n Hash.prototype.has = hashHas;\n Hash.prototype.set = hashSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an list cache object.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function ListCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the list cache.\n *\n * @private\n * @name clear\n * @memberOf ListCache\n */\n function listCacheClear() {\n this.__data__ = [];\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the list cache.\n *\n * @private\n * @name delete\n * @memberOf ListCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function listCacheDelete(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n return false;\n }\n var lastIndex = data.length - 1;\n if (index == lastIndex) {\n data.pop();\n } else {\n splice.call(data, index, 1);\n }\n --this.size;\n return true;\n }\n\n /**\n * Gets the list cache value for `key`.\n *\n * @private\n * @name get\n * @memberOf ListCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function listCacheGet(key) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n return index < 0 ? undefined : data[index][1];\n }\n\n /**\n * Checks if a list cache value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf ListCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function listCacheHas(key) {\n return assocIndexOf(this.__data__, key) > -1;\n }\n\n /**\n * Sets the list cache `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf ListCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the list cache instance.\n */\n function listCacheSet(key, value) {\n var data = this.__data__,\n index = assocIndexOf(data, key);\n\n if (index < 0) {\n ++this.size;\n data.push([key, value]);\n } else {\n data[index][1] = value;\n }\n return this;\n }\n\n // Add methods to `ListCache`.\n ListCache.prototype.clear = listCacheClear;\n ListCache.prototype['delete'] = listCacheDelete;\n ListCache.prototype.get = listCacheGet;\n ListCache.prototype.has = listCacheHas;\n ListCache.prototype.set = listCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a map cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function MapCache(entries) {\n var index = -1,\n length = entries == null ? 0 : entries.length;\n\n this.clear();\n while (++index < length) {\n var entry = entries[index];\n this.set(entry[0], entry[1]);\n }\n }\n\n /**\n * Removes all key-value entries from the map.\n *\n * @private\n * @name clear\n * @memberOf MapCache\n */\n function mapCacheClear() {\n this.size = 0;\n this.__data__ = {\n 'hash': new Hash,\n 'map': new (Map || ListCache),\n 'string': new Hash\n };\n }\n\n /**\n * Removes `key` and its value from the map.\n *\n * @private\n * @name delete\n * @memberOf MapCache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function mapCacheDelete(key) {\n var result = getMapData(this, key)['delete'](key);\n this.size -= result ? 1 : 0;\n return result;\n }\n\n /**\n * Gets the map value for `key`.\n *\n * @private\n * @name get\n * @memberOf MapCache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function mapCacheGet(key) {\n return getMapData(this, key).get(key);\n }\n\n /**\n * Checks if a map value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf MapCache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function mapCacheHas(key) {\n return getMapData(this, key).has(key);\n }\n\n /**\n * Sets the map `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf MapCache\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the map cache instance.\n */\n function mapCacheSet(key, value) {\n var data = getMapData(this, key),\n size = data.size;\n\n data.set(key, value);\n this.size += data.size == size ? 0 : 1;\n return this;\n }\n\n // Add methods to `MapCache`.\n MapCache.prototype.clear = mapCacheClear;\n MapCache.prototype['delete'] = mapCacheDelete;\n MapCache.prototype.get = mapCacheGet;\n MapCache.prototype.has = mapCacheHas;\n MapCache.prototype.set = mapCacheSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n *\n * Creates an array cache object to store unique values.\n *\n * @private\n * @constructor\n * @param {Array} [values] The values to cache.\n */\n function SetCache(values) {\n var index = -1,\n length = values == null ? 0 : values.length;\n\n this.__data__ = new MapCache;\n while (++index < length) {\n this.add(values[index]);\n }\n }\n\n /**\n * Adds `value` to the array cache.\n *\n * @private\n * @name add\n * @memberOf SetCache\n * @alias push\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache instance.\n */\n function setCacheAdd(value) {\n this.__data__.set(value, HASH_UNDEFINED);\n return this;\n }\n\n /**\n * Checks if `value` is in the array cache.\n *\n * @private\n * @name has\n * @memberOf SetCache\n * @param {*} value The value to search for.\n * @returns {number} Returns `true` if `value` is found, else `false`.\n */\n function setCacheHas(value) {\n return this.__data__.has(value);\n }\n\n // Add methods to `SetCache`.\n SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;\n SetCache.prototype.has = setCacheHas;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a stack cache object to store key-value pairs.\n *\n * @private\n * @constructor\n * @param {Array} [entries] The key-value pairs to cache.\n */\n function Stack(entries) {\n var data = this.__data__ = new ListCache(entries);\n this.size = data.size;\n }\n\n /**\n * Removes all key-value entries from the stack.\n *\n * @private\n * @name clear\n * @memberOf Stack\n */\n function stackClear() {\n this.__data__ = new ListCache;\n this.size = 0;\n }\n\n /**\n * Removes `key` and its value from the stack.\n *\n * @private\n * @name delete\n * @memberOf Stack\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed, else `false`.\n */\n function stackDelete(key) {\n var data = this.__data__,\n result = data['delete'](key);\n\n this.size = data.size;\n return result;\n }\n\n /**\n * Gets the stack value for `key`.\n *\n * @private\n * @name get\n * @memberOf Stack\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the entry value.\n */\n function stackGet(key) {\n return this.__data__.get(key);\n }\n\n /**\n * Checks if a stack value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf Stack\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function stackHas(key) {\n return this.__data__.has(key);\n }\n\n /**\n * Sets the stack `key` to `value`.\n *\n * @private\n * @name set\n * @memberOf Stack\n * @param {string} key The key of the value to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns the stack cache instance.\n */\n function stackSet(key, value) {\n var data = this.__data__;\n if (data instanceof ListCache) {\n var pairs = data.__data__;\n if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {\n pairs.push([key, value]);\n this.size = ++data.size;\n return this;\n }\n data = this.__data__ = new MapCache(pairs);\n }\n data.set(key, value);\n this.size = data.size;\n return this;\n }\n\n // Add methods to `Stack`.\n Stack.prototype.clear = stackClear;\n Stack.prototype['delete'] = stackDelete;\n Stack.prototype.get = stackGet;\n Stack.prototype.has = stackHas;\n Stack.prototype.set = stackSet;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of the enumerable property names of the array-like `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @param {boolean} inherited Specify returning inherited property names.\n * @returns {Array} Returns the array of property names.\n */\n function arrayLikeKeys(value, inherited) {\n var isArr = isArray(value),\n isArg = !isArr && isArguments(value),\n isBuff = !isArr && !isArg && isBuffer(value),\n isType = !isArr && !isArg && !isBuff && isTypedArray(value),\n skipIndexes = isArr || isArg || isBuff || isType,\n result = skipIndexes ? baseTimes(value.length, String) : [],\n length = result.length;\n\n for (var key in value) {\n if ((inherited || hasOwnProperty.call(value, key)) &&\n !(skipIndexes && (\n // Safari 9 has enumerable `arguments.length` in strict mode.\n key == 'length' ||\n // Node.js 0.10 has enumerable non-index properties on buffers.\n (isBuff && (key == 'offset' || key == 'parent')) ||\n // PhantomJS 2 has enumerable non-index properties on typed arrays.\n (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||\n // Skip index properties.\n isIndex(key, length)\n ))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.sample` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @returns {*} Returns the random element.\n */\n function arraySample(array) {\n var length = array.length;\n return length ? array[baseRandom(0, length - 1)] : undefined;\n }\n\n /**\n * A specialized version of `_.sampleSize` for arrays.\n *\n * @private\n * @param {Array} array The array to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function arraySampleSize(array, n) {\n return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));\n }\n\n /**\n * A specialized version of `_.shuffle` for arrays.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function arrayShuffle(array) {\n return shuffleSelf(copyArray(array));\n }\n\n /**\n * This function is like `assignValue` except that it doesn't assign\n * `undefined` values.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignMergeValue(object, key, value) {\n if ((value !== undefined && !eq(object[key], value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Assigns `value` to `key` of `object` if the existing value is not equivalent\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function assignValue(object, key, value) {\n var objValue = object[key];\n if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||\n (value === undefined && !(key in object))) {\n baseAssignValue(object, key, value);\n }\n }\n\n /**\n * Gets the index at which the `key` is found in `array` of key-value pairs.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {*} key The key to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function assocIndexOf(array, key) {\n var length = array.length;\n while (length--) {\n if (eq(array[length][0], key)) {\n return length;\n }\n }\n return -1;\n }\n\n /**\n * Aggregates elements of `collection` on `accumulator` with keys transformed\n * by `iteratee` and values set by `setter`.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform keys.\n * @param {Object} accumulator The initial aggregated object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseAggregator(collection, setter, iteratee, accumulator) {\n baseEach(collection, function(value, key, collection) {\n setter(accumulator, value, iteratee(value), collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.assign` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssign(object, source) {\n return object && copyObject(source, keys(source), object);\n }\n\n /**\n * The base implementation of `_.assignIn` without support for multiple sources\n * or `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @returns {Object} Returns `object`.\n */\n function baseAssignIn(object, source) {\n return object && copyObject(source, keysIn(source), object);\n }\n\n /**\n * The base implementation of `assignValue` and `assignMergeValue` without\n * value checks.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {string} key The key of the property to assign.\n * @param {*} value The value to assign.\n */\n function baseAssignValue(object, key, value) {\n if (key == '__proto__' && defineProperty) {\n defineProperty(object, key, {\n 'configurable': true,\n 'enumerable': true,\n 'value': value,\n 'writable': true\n });\n } else {\n object[key] = value;\n }\n }\n\n /**\n * The base implementation of `_.at` without support for individual paths.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {string[]} paths The property paths to pick.\n * @returns {Array} Returns the picked elements.\n */\n function baseAt(object, paths) {\n var index = -1,\n length = paths.length,\n result = Array(length),\n skip = object == null;\n\n while (++index < length) {\n result[index] = skip ? undefined : get(object, paths[index]);\n }\n return result;\n }\n\n /**\n * The base implementation of `_.clamp` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n */\n function baseClamp(number, lower, upper) {\n if (number === number) {\n if (upper !== undefined) {\n number = number <= upper ? number : upper;\n }\n if (lower !== undefined) {\n number = number >= lower ? number : lower;\n }\n }\n return number;\n }\n\n /**\n * The base implementation of `_.clone` and `_.cloneDeep` which tracks\n * traversed objects.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Deep clone\n * 2 - Flatten inherited properties\n * 4 - Clone symbols\n * @param {Function} [customizer] The function to customize cloning.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The parent object of `value`.\n * @param {Object} [stack] Tracks traversed objects and their clone counterparts.\n * @returns {*} Returns the cloned value.\n */\n function baseClone(value, bitmask, customizer, key, object, stack) {\n var result,\n isDeep = bitmask & CLONE_DEEP_FLAG,\n isFlat = bitmask & CLONE_FLAT_FLAG,\n isFull = bitmask & CLONE_SYMBOLS_FLAG;\n\n if (customizer) {\n result = object ? customizer(value, key, object, stack) : customizer(value);\n }\n if (result !== undefined) {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return copyArray(value, result);\n }\n } else {\n var tag = getTag(value),\n isFunc = tag == funcTag || tag == genTag;\n\n if (isBuffer(value)) {\n return cloneBuffer(value, isDeep);\n }\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = (isFlat || isFunc) ? {} : initCloneObject(value);\n if (!isDeep) {\n return isFlat\n ? copySymbolsIn(value, baseAssignIn(result, value))\n : copySymbols(value, baseAssign(result, value));\n }\n } else {\n if (!cloneableTags[tag]) {\n return object ? value : {};\n }\n result = initCloneByTag(value, tag, isDeep);\n }\n }\n // Check for circular references and return its corresponding clone.\n stack || (stack = new Stack);\n var stacked = stack.get(value);\n if (stacked) {\n return stacked;\n }\n stack.set(value, result);\n\n if (isSet(value)) {\n value.forEach(function(subValue) {\n result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));\n });\n } else if (isMap(value)) {\n value.forEach(function(subValue, key) {\n result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n }\n\n var keysFunc = isFull\n ? (isFlat ? getAllKeysIn : getAllKeys)\n : (isFlat ? keysIn : keys);\n\n var props = isArr ? undefined : keysFunc(value);\n arrayEach(props || value, function(subValue, key) {\n if (props) {\n key = subValue;\n subValue = value[key];\n }\n // Recursively populate clone (susceptible to call stack limits).\n assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));\n });\n return result;\n }\n\n /**\n * The base implementation of `_.conforms` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property predicates to conform to.\n * @returns {Function} Returns the new spec function.\n */\n function baseConforms(source) {\n var props = keys(source);\n return function(object) {\n return baseConformsTo(object, source, props);\n };\n }\n\n /**\n * The base implementation of `_.conformsTo` which accepts `props` to check.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n */\n function baseConformsTo(object, source, props) {\n var length = props.length;\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (length--) {\n var key = props[length],\n predicate = source[key],\n value = object[key];\n\n if ((value === undefined && !(key in object)) || !predicate(value)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.delay` and `_.defer` which accepts `args`\n * to provide to `func`.\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {Array} args The arguments to provide to `func`.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n function baseDelay(func, wait, args) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return setTimeout(function() { func.apply(undefined, args); }, wait);\n }\n\n /**\n * The base implementation of methods like `_.difference` without support\n * for excluding multiple arrays or iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n */\n function baseDifference(array, values, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n isCommon = true,\n length = array.length,\n result = [],\n valuesLength = values.length;\n\n if (!length) {\n return result;\n }\n if (iteratee) {\n values = arrayMap(values, baseUnary(iteratee));\n }\n if (comparator) {\n includes = arrayIncludesWith;\n isCommon = false;\n }\n else if (values.length >= LARGE_ARRAY_SIZE) {\n includes = cacheHas;\n isCommon = false;\n values = new SetCache(values);\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee == null ? value : iteratee(value);\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === computed) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (!includes(values, computed, comparator)) {\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.forEach` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEach = createBaseEach(baseForOwn);\n\n /**\n * The base implementation of `_.forEachRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n */\n var baseEachRight = createBaseEach(baseForOwnRight, true);\n\n /**\n * The base implementation of `_.every` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\n function baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function(value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n }\n\n /**\n * The base implementation of methods like `_.max` and `_.min` which accepts a\n * `comparator` to determine the extremum value.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The iteratee invoked per iteration.\n * @param {Function} comparator The comparator used to compare values.\n * @returns {*} Returns the extremum value.\n */\n function baseExtremum(array, iteratee, comparator) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n var value = array[index],\n current = iteratee(value);\n\n if (current != null && (computed === undefined\n ? (current === current && !isSymbol(current))\n : comparator(current, computed)\n )) {\n var computed = current,\n result = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.fill` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n */\n function baseFill(array, value, start, end) {\n var length = array.length;\n\n start = toInteger(start);\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = (end === undefined || end > length) ? length : toInteger(end);\n if (end < 0) {\n end += length;\n }\n end = start > end ? 0 : toLength(end);\n while (start < end) {\n array[start++] = value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.filter` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function baseFilter(collection, predicate) {\n var result = [];\n baseEach(collection, function(value, index, collection) {\n if (predicate(value, index, collection)) {\n result.push(value);\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.flatten` with support for restricting flattening.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {number} depth The maximum recursion depth.\n * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.\n * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.\n * @param {Array} [result=[]] The initial result value.\n * @returns {Array} Returns the new flattened array.\n */\n function baseFlatten(array, depth, predicate, isStrict, result) {\n var index = -1,\n length = array.length;\n\n predicate || (predicate = isFlattenable);\n result || (result = []);\n\n while (++index < length) {\n var value = array[index];\n if (depth > 0 && predicate(value)) {\n if (depth > 1) {\n // Recursively flatten arrays (susceptible to call stack limits).\n baseFlatten(value, depth - 1, predicate, isStrict, result);\n } else {\n arrayPush(result, value);\n }\n } else if (!isStrict) {\n result[result.length] = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `baseForOwn` which iterates over `object`\n * properties returned by `keysFunc` and invokes `iteratee` for each property.\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseFor = createBaseFor();\n\n /**\n * This function is like `baseFor` except that it iterates over properties\n * in the opposite order.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n var baseForRight = createBaseFor(true);\n\n /**\n * The base implementation of `_.forOwn` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwn(object, iteratee) {\n return object && baseFor(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.forOwnRight` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwnRight(object, iteratee) {\n return object && baseForRight(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.functions` which creates an array of\n * `object` function property names filtered from `props`.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Array} props The property names to filter.\n * @returns {Array} Returns the function names.\n */\n function baseFunctions(object, props) {\n return arrayFilter(props, function(key) {\n return isFunction(object[key]);\n });\n }\n\n /**\n * The base implementation of `_.get` without support for default values.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @returns {*} Returns the resolved value.\n */\n function baseGet(object, path) {\n path = castPath(path, object);\n\n var index = 0,\n length = path.length;\n\n while (object != null && index < length) {\n object = object[toKey(path[index++])];\n }\n return (index && index == length) ? object : undefined;\n }\n\n /**\n * The base implementation of `getAllKeys` and `getAllKeysIn` which uses\n * `keysFunc` and `symbolsFunc` to get the enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @param {Function} symbolsFunc The function to get the symbols of `object`.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function baseGetAllKeys(object, keysFunc, symbolsFunc) {\n var result = keysFunc(object);\n return isArray(object) ? result : arrayPush(result, symbolsFunc(object));\n }\n\n /**\n * The base implementation of `getTag` without fallbacks for buggy environments.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n function baseGetTag(value) {\n if (value == null) {\n return value === undefined ? undefinedTag : nullTag;\n }\n return (symToStringTag && symToStringTag in Object(value))\n ? getRawTag(value)\n : objectToString(value);\n }\n\n /**\n * The base implementation of `_.gt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n */\n function baseGt(value, other) {\n return value > other;\n }\n\n /**\n * The base implementation of `_.has` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHas(object, key) {\n return object != null && hasOwnProperty.call(object, key);\n }\n\n /**\n * The base implementation of `_.hasIn` without support for deep paths.\n *\n * @private\n * @param {Object} [object] The object to query.\n * @param {Array|string} key The key to check.\n * @returns {boolean} Returns `true` if `key` exists, else `false`.\n */\n function baseHasIn(object, key) {\n return object != null && key in Object(object);\n }\n\n /**\n * The base implementation of `_.inRange` which doesn't coerce arguments.\n *\n * @private\n * @param {number} number The number to check.\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n */\n function baseInRange(number, start, end) {\n return number >= nativeMin(start, end) && number < nativeMax(start, end);\n }\n\n /**\n * The base implementation of methods like `_.intersection`, without support\n * for iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of shared values.\n */\n function baseIntersection(arrays, iteratee, comparator) {\n var includes = comparator ? arrayIncludesWith : arrayIncludes,\n length = arrays[0].length,\n othLength = arrays.length,\n othIndex = othLength,\n caches = Array(othLength),\n maxLength = Infinity,\n result = [];\n\n while (othIndex--) {\n var array = arrays[othIndex];\n if (othIndex && iteratee) {\n array = arrayMap(array, baseUnary(iteratee));\n }\n maxLength = nativeMin(array.length, maxLength);\n caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))\n ? new SetCache(othIndex && array)\n : undefined;\n }\n array = arrays[0];\n\n var index = -1,\n seen = caches[0];\n\n outer:\n while (++index < length && result.length < maxLength) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (!(seen\n ? cacheHas(seen, computed)\n : includes(result, computed, comparator)\n )) {\n othIndex = othLength;\n while (--othIndex) {\n var cache = caches[othIndex];\n if (!(cache\n ? cacheHas(cache, computed)\n : includes(arrays[othIndex], computed, comparator))\n ) {\n continue outer;\n }\n }\n if (seen) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.invert` and `_.invertBy` which inverts\n * `object` with values transformed by `iteratee` and set by `setter`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} setter The function to set `accumulator` values.\n * @param {Function} iteratee The iteratee to transform values.\n * @param {Object} accumulator The initial inverted object.\n * @returns {Function} Returns `accumulator`.\n */\n function baseInverter(object, setter, iteratee, accumulator) {\n baseForOwn(object, function(value, key, object) {\n setter(accumulator, iteratee(value), key, object);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `_.invoke` without support for individual\n * method arguments.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {Array} args The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n */\n function baseInvoke(object, path, args) {\n path = castPath(path, object);\n object = parent(object, path);\n var func = object == null ? object : object[toKey(last(path))];\n return func == null ? undefined : apply(func, object, args);\n }\n\n /**\n * The base implementation of `_.isArguments`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n */\n function baseIsArguments(value) {\n return isObjectLike(value) && baseGetTag(value) == argsTag;\n }\n\n /**\n * The base implementation of `_.isArrayBuffer` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n */\n function baseIsArrayBuffer(value) {\n return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;\n }\n\n /**\n * The base implementation of `_.isDate` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n */\n function baseIsDate(value) {\n return isObjectLike(value) && baseGetTag(value) == dateTag;\n }\n\n /**\n * The base implementation of `_.isEqual` which supports partial comparisons\n * and tracks traversed objects.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {boolean} bitmask The bitmask flags.\n * 1 - Unordered comparison\n * 2 - Partial comparison\n * @param {Function} [customizer] The function to customize comparisons.\n * @param {Object} [stack] Tracks traversed `value` and `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\n function baseIsEqual(value, other, bitmask, customizer, stack) {\n if (value === other) {\n return true;\n }\n if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);\n }\n\n /**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} [stack] Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = objIsArr ? arrayTag : getTag(object),\n othTag = othIsArr ? arrayTag : getTag(other);\n\n objTag = objTag == argsTag ? objectTag : objTag;\n othTag = othTag == argsTag ? objectTag : othTag;\n\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && isBuffer(object)) {\n if (!isBuffer(other)) {\n return false;\n }\n objIsArr = true;\n objIsObj = false;\n }\n if (isSameTag && !objIsObj) {\n stack || (stack = new Stack);\n return (objIsArr || isTypedArray(object))\n ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)\n : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);\n }\n if (!(bitmask & COMPARE_PARTIAL_FLAG)) {\n var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (objIsWrapped || othIsWrapped) {\n var objUnwrapped = objIsWrapped ? object.value() : object,\n othUnwrapped = othIsWrapped ? other.value() : other;\n\n stack || (stack = new Stack);\n return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);\n }\n }\n if (!isSameTag) {\n return false;\n }\n stack || (stack = new Stack);\n return equalObjects(object, other, bitmask, customizer, equalFunc, stack);\n }\n\n /**\n * The base implementation of `_.isMap` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n */\n function baseIsMap(value) {\n return isObjectLike(value) && getTag(value) == mapTag;\n }\n\n /**\n * The base implementation of `_.isMatch` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Array} matchData The property names, values, and compare flags to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\n function baseIsMatch(object, source, matchData, customizer) {\n var index = matchData.length,\n length = index,\n noCustomizer = !customizer;\n\n if (object == null) {\n return !length;\n }\n object = Object(object);\n while (index--) {\n var data = matchData[index];\n if ((noCustomizer && data[2])\n ? data[1] !== object[data[0]]\n : !(data[0] in object)\n ) {\n return false;\n }\n }\n while (++index < length) {\n data = matchData[index];\n var key = data[0],\n objValue = object[key],\n srcValue = data[1];\n\n if (noCustomizer && data[2]) {\n if (objValue === undefined && !(key in object)) {\n return false;\n }\n } else {\n var stack = new Stack;\n if (customizer) {\n var result = customizer(objValue, srcValue, key, object, source, stack);\n }\n if (!(result === undefined\n ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)\n : result\n )) {\n return false;\n }\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.isNative` without bad shim checks.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n */\n function baseIsNative(value) {\n if (!isObject(value) || isMasked(value)) {\n return false;\n }\n var pattern = isFunction(value) ? reIsNative : reIsHostCtor;\n return pattern.test(toSource(value));\n }\n\n /**\n * The base implementation of `_.isRegExp` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n */\n function baseIsRegExp(value) {\n return isObjectLike(value) && baseGetTag(value) == regexpTag;\n }\n\n /**\n * The base implementation of `_.isSet` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n */\n function baseIsSet(value) {\n return isObjectLike(value) && getTag(value) == setTag;\n }\n\n /**\n * The base implementation of `_.isTypedArray` without Node.js optimizations.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n */\n function baseIsTypedArray(value) {\n return isObjectLike(value) &&\n isLength(value.length) && !!typedArrayTags[baseGetTag(value)];\n }\n\n /**\n * The base implementation of `_.iteratee`.\n *\n * @private\n * @param {*} [value=_.identity] The value to convert to an iteratee.\n * @returns {Function} Returns the iteratee.\n */\n function baseIteratee(value) {\n // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.\n // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.\n if (typeof value == 'function') {\n return value;\n }\n if (value == null) {\n return identity;\n }\n if (typeof value == 'object') {\n return isArray(value)\n ? baseMatchesProperty(value[0], value[1])\n : baseMatches(value);\n }\n return property(value);\n }\n\n /**\n * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeys(object) {\n if (!isPrototype(object)) {\n return nativeKeys(object);\n }\n var result = [];\n for (var key in Object(object)) {\n if (hasOwnProperty.call(object, key) && key != 'constructor') {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function baseKeysIn(object) {\n if (!isObject(object)) {\n return nativeKeysIn(object);\n }\n var isProto = isPrototype(object),\n result = [];\n\n for (var key in object) {\n if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.lt` which doesn't coerce arguments.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n */\n function baseLt(value, other) {\n return value < other;\n }\n\n /**\n * The base implementation of `_.map` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function baseMap(collection, iteratee) {\n var index = -1,\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value, key, collection) {\n result[++index] = iteratee(value, key, collection);\n });\n return result;\n }\n\n /**\n * The base implementation of `_.matches` which doesn't clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatches(source) {\n var matchData = getMatchData(source);\n if (matchData.length == 1 && matchData[0][2]) {\n return matchesStrictComparable(matchData[0][0], matchData[0][1]);\n }\n return function(object) {\n return object === source || baseIsMatch(object, source, matchData);\n };\n }\n\n /**\n * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.\n *\n * @private\n * @param {string} path The path of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function baseMatchesProperty(path, srcValue) {\n if (isKey(path) && isStrictComparable(srcValue)) {\n return matchesStrictComparable(toKey(path), srcValue);\n }\n return function(object) {\n var objValue = get(object, path);\n return (objValue === undefined && objValue === srcValue)\n ? hasIn(object, path)\n : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);\n };\n }\n\n /**\n * The base implementation of `_.merge` without support for multiple sources.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} [customizer] The function to customize merged values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMerge(object, source, srcIndex, customizer, stack) {\n if (object === source) {\n return;\n }\n baseFor(source, function(srcValue, key) {\n stack || (stack = new Stack);\n if (isObject(srcValue)) {\n baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);\n }\n else {\n var newValue = customizer\n ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)\n : undefined;\n\n if (newValue === undefined) {\n newValue = srcValue;\n }\n assignMergeValue(object, key, newValue);\n }\n }, keysIn);\n }\n\n /**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {number} srcIndex The index of `source`.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize assigned values.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n */\n function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {\n var objValue = safeGet(object, key),\n srcValue = safeGet(source, key),\n stacked = stack.get(srcValue);\n\n if (stacked) {\n assignMergeValue(object, key, stacked);\n return;\n }\n var newValue = customizer\n ? customizer(objValue, srcValue, (key + ''), object, source, stack)\n : undefined;\n\n var isCommon = newValue === undefined;\n\n if (isCommon) {\n var isArr = isArray(srcValue),\n isBuff = !isArr && isBuffer(srcValue),\n isTyped = !isArr && !isBuff && isTypedArray(srcValue);\n\n newValue = srcValue;\n if (isArr || isBuff || isTyped) {\n if (isArray(objValue)) {\n newValue = objValue;\n }\n else if (isArrayLikeObject(objValue)) {\n newValue = copyArray(objValue);\n }\n else if (isBuff) {\n isCommon = false;\n newValue = cloneBuffer(srcValue, true);\n }\n else if (isTyped) {\n isCommon = false;\n newValue = cloneTypedArray(srcValue, true);\n }\n else {\n newValue = [];\n }\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n newValue = objValue;\n if (isArguments(objValue)) {\n newValue = toPlainObject(objValue);\n }\n else if (!isObject(objValue) || isFunction(objValue)) {\n newValue = initCloneObject(srcValue);\n }\n }\n else {\n isCommon = false;\n }\n }\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, newValue);\n mergeFunc(newValue, srcValue, srcIndex, customizer, stack);\n stack['delete'](srcValue);\n }\n assignMergeValue(object, key, newValue);\n }\n\n /**\n * The base implementation of `_.nth` which doesn't coerce arguments.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {number} n The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n */\n function baseNth(array, n) {\n var length = array.length;\n if (!length) {\n return;\n }\n n += n < 0 ? length : 0;\n return isIndex(n, length) ? array[n] : undefined;\n }\n\n /**\n * The base implementation of `_.orderBy` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.\n * @param {string[]} orders The sort orders of `iteratees`.\n * @returns {Array} Returns the new sorted array.\n */\n function baseOrderBy(collection, iteratees, orders) {\n if (iteratees.length) {\n iteratees = arrayMap(iteratees, function(iteratee) {\n if (isArray(iteratee)) {\n return function(value) {\n return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);\n }\n }\n return iteratee;\n });\n } else {\n iteratees = [identity];\n }\n\n var index = -1;\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n\n var result = baseMap(collection, function(value, key, collection) {\n var criteria = arrayMap(iteratees, function(iteratee) {\n return iteratee(value);\n });\n return { 'criteria': criteria, 'index': ++index, 'value': value };\n });\n\n return baseSortBy(result, function(object, other) {\n return compareMultiple(object, other, orders);\n });\n }\n\n /**\n * The base implementation of `_.pick` without support for individual\n * property identifiers.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @returns {Object} Returns the new object.\n */\n function basePick(object, paths) {\n return basePickBy(object, paths, function(value, path) {\n return hasIn(object, path);\n });\n }\n\n /**\n * The base implementation of `_.pickBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} paths The property paths to pick.\n * @param {Function} predicate The function invoked per property.\n * @returns {Object} Returns the new object.\n */\n function basePickBy(object, paths, predicate) {\n var index = -1,\n length = paths.length,\n result = {};\n\n while (++index < length) {\n var path = paths[index],\n value = baseGet(object, path);\n\n if (predicate(value, path)) {\n baseSet(result, castPath(path, object), value);\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `baseProperty` which supports deep paths.\n *\n * @private\n * @param {Array|string} path The path of the property to get.\n * @returns {Function} Returns the new accessor function.\n */\n function basePropertyDeep(path) {\n return function(object) {\n return baseGet(object, path);\n };\n }\n\n /**\n * The base implementation of `_.pullAllBy` without support for iteratee\n * shorthands.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n */\n function basePullAll(array, values, iteratee, comparator) {\n var indexOf = comparator ? baseIndexOfWith : baseIndexOf,\n index = -1,\n length = values.length,\n seen = array;\n\n if (array === values) {\n values = copyArray(values);\n }\n if (iteratee) {\n seen = arrayMap(array, baseUnary(iteratee));\n }\n while (++index < length) {\n var fromIndex = 0,\n value = values[index],\n computed = iteratee ? iteratee(value) : value;\n\n while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {\n if (seen !== array) {\n splice.call(seen, fromIndex, 1);\n }\n splice.call(array, fromIndex, 1);\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.pullAt` without support for individual\n * indexes or capturing the removed elements.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {number[]} indexes The indexes of elements to remove.\n * @returns {Array} Returns `array`.\n */\n function basePullAt(array, indexes) {\n var length = array ? indexes.length : 0,\n lastIndex = length - 1;\n\n while (length--) {\n var index = indexes[length];\n if (length == lastIndex || index !== previous) {\n var previous = index;\n if (isIndex(index)) {\n splice.call(array, index, 1);\n } else {\n baseUnset(array, index);\n }\n }\n }\n return array;\n }\n\n /**\n * The base implementation of `_.random` without support for returning\n * floating-point numbers.\n *\n * @private\n * @param {number} lower The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the random number.\n */\n function baseRandom(lower, upper) {\n return lower + nativeFloor(nativeRandom() * (upper - lower + 1));\n }\n\n /**\n * The base implementation of `_.range` and `_.rangeRight` which doesn't\n * coerce arguments.\n *\n * @private\n * @param {number} start The start of the range.\n * @param {number} end The end of the range.\n * @param {number} step The value to increment or decrement by.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the range of numbers.\n */\n function baseRange(start, end, step, fromRight) {\n var index = -1,\n length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),\n result = Array(length);\n\n while (length--) {\n result[fromRight ? length : ++index] = start;\n start += step;\n }\n return result;\n }\n\n /**\n * The base implementation of `_.repeat` which doesn't coerce arguments.\n *\n * @private\n * @param {string} string The string to repeat.\n * @param {number} n The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n */\n function baseRepeat(string, n) {\n var result = '';\n if (!string || n < 1 || n > MAX_SAFE_INTEGER) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = nativeFloor(n / 2);\n if (n) {\n string += string;\n }\n } while (n);\n\n return result;\n }\n\n /**\n * The base implementation of `_.rest` which doesn't validate or coerce arguments.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n */\n function baseRest(func, start) {\n return setToString(overRest(func, start, identity), func + '');\n }\n\n /**\n * The base implementation of `_.sample`.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n */\n function baseSample(collection) {\n return arraySample(values(collection));\n }\n\n /**\n * The base implementation of `_.sampleSize` without param guards.\n *\n * @private\n * @param {Array|Object} collection The collection to sample.\n * @param {number} n The number of elements to sample.\n * @returns {Array} Returns the random elements.\n */\n function baseSampleSize(collection, n) {\n var array = values(collection);\n return shuffleSelf(array, baseClamp(n, 0, array.length));\n }\n\n /**\n * The base implementation of `_.set`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseSet(object, path, value, customizer) {\n if (!isObject(object)) {\n return object;\n }\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n lastIndex = length - 1,\n nested = object;\n\n while (nested != null && ++index < length) {\n var key = toKey(path[index]),\n newValue = value;\n\n if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n return object;\n }\n\n if (index != lastIndex) {\n var objValue = nested[key];\n newValue = customizer ? customizer(objValue, key, nested) : undefined;\n if (newValue === undefined) {\n newValue = isObject(objValue)\n ? objValue\n : (isIndex(path[index + 1]) ? [] : {});\n }\n }\n assignValue(nested, key, newValue);\n nested = nested[key];\n }\n return object;\n }\n\n /**\n * The base implementation of `setData` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var baseSetData = !metaMap ? identity : function(func, data) {\n metaMap.set(func, data);\n return func;\n };\n\n /**\n * The base implementation of `setToString` without support for hot loop shorting.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var baseSetToString = !defineProperty ? identity : function(func, string) {\n return defineProperty(func, 'toString', {\n 'configurable': true,\n 'enumerable': false,\n 'value': constant(string),\n 'writable': true\n });\n };\n\n /**\n * The base implementation of `_.shuffle`.\n *\n * @private\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n */\n function baseShuffle(collection) {\n return shuffleSelf(values(collection));\n }\n\n /**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = end > length ? length : end;\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : ((end - start) >>> 0);\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n }\n\n /**\n * The base implementation of `_.some` without support for iteratee shorthands.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function baseSome(collection, predicate) {\n var result;\n\n baseEach(collection, function(value, index, collection) {\n result = predicate(value, index, collection);\n return !result;\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which\n * performs a binary search of `array` to determine the index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndex(array, value, retHighest) {\n var low = 0,\n high = array == null ? low : array.length;\n\n if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = array[mid];\n\n if (computed !== null && !isSymbol(computed) &&\n (retHighest ? (computed <= value) : (computed < value))) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n return baseSortedIndexBy(array, value, identity, retHighest);\n }\n\n /**\n * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`\n * which invokes `iteratee` for `value` and each element of `array` to compute\n * their sort ranking. The iteratee is invoked with one argument; (value).\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iteratee The iteratee invoked per element.\n * @param {boolean} [retHighest] Specify returning the highest qualified index.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function baseSortedIndexBy(array, value, iteratee, retHighest) {\n var low = 0,\n high = array == null ? 0 : array.length;\n if (high === 0) {\n return 0;\n }\n\n value = iteratee(value);\n var valIsNaN = value !== value,\n valIsNull = value === null,\n valIsSymbol = isSymbol(value),\n valIsUndefined = value === undefined;\n\n while (low < high) {\n var mid = nativeFloor((low + high) / 2),\n computed = iteratee(array[mid]),\n othIsDefined = computed !== undefined,\n othIsNull = computed === null,\n othIsReflexive = computed === computed,\n othIsSymbol = isSymbol(computed);\n\n if (valIsNaN) {\n var setLow = retHighest || othIsReflexive;\n } else if (valIsUndefined) {\n setLow = othIsReflexive && (retHighest || othIsDefined);\n } else if (valIsNull) {\n setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);\n } else if (valIsSymbol) {\n setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);\n } else if (othIsNull || othIsSymbol) {\n setLow = false;\n } else {\n setLow = retHighest ? (computed <= value) : (computed < value);\n }\n if (setLow) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return nativeMin(high, MAX_ARRAY_INDEX);\n }\n\n /**\n * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without\n * support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseSortedUniq(array, iteratee) {\n var index = -1,\n length = array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n if (!index || !eq(computed, seen)) {\n var seen = computed;\n result[resIndex++] = value === 0 ? 0 : value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.toNumber` which doesn't ensure correct\n * conversions of binary, hexadecimal, or octal string values.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n */\n function baseToNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n return +value;\n }\n\n /**\n * The base implementation of `_.toString` which doesn't convert nullish\n * values to empty strings.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\n function baseToString(value) {\n // Exit early for strings to avoid a performance hit in some environments.\n if (typeof value == 'string') {\n return value;\n }\n if (isArray(value)) {\n // Recursively convert values (susceptible to call stack limits).\n return arrayMap(value, baseToString) + '';\n }\n if (isSymbol(value)) {\n return symbolToString ? symbolToString.call(value) : '';\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * The base implementation of `_.uniqBy` without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n */\n function baseUniq(array, iteratee, comparator) {\n var index = -1,\n includes = arrayIncludes,\n length = array.length,\n isCommon = true,\n result = [],\n seen = result;\n\n if (comparator) {\n isCommon = false;\n includes = arrayIncludesWith;\n }\n else if (length >= LARGE_ARRAY_SIZE) {\n var set = iteratee ? null : createSet(array);\n if (set) {\n return setToArray(set);\n }\n isCommon = false;\n includes = cacheHas;\n seen = new SetCache;\n }\n else {\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value) : value;\n\n value = (comparator || value !== 0) ? value : 0;\n if (isCommon && computed === computed) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (!includes(seen, computed, comparator)) {\n if (seen !== result) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.unset`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The property path to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n */\n function baseUnset(object, path) {\n path = castPath(path, object);\n object = parent(object, path);\n return object == null || delete object[toKey(last(path))];\n }\n\n /**\n * The base implementation of `_.update`.\n *\n * @private\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to update.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize path creation.\n * @returns {Object} Returns `object`.\n */\n function baseUpdate(object, path, updater, customizer) {\n return baseSet(object, path, updater(baseGet(object, path)), customizer);\n }\n\n /**\n * The base implementation of methods like `_.dropWhile` and `_.takeWhile`\n * without support for iteratee shorthands.\n *\n * @private\n * @param {Array} array The array to query.\n * @param {Function} predicate The function invoked per iteration.\n * @param {boolean} [isDrop] Specify dropping elements instead of taking them.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseWhile(array, predicate, isDrop, fromRight) {\n var length = array.length,\n index = fromRight ? length : -1;\n\n while ((fromRight ? index-- : ++index < length) &&\n predicate(array[index], index, array)) {}\n\n return isDrop\n ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))\n : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));\n }\n\n /**\n * The base implementation of `wrapperValue` which returns the result of\n * performing a sequence of actions on the unwrapped `value`, where each\n * successive action is supplied the return value of the previous.\n *\n * @private\n * @param {*} value The unwrapped value.\n * @param {Array} actions Actions to perform to resolve the unwrapped value.\n * @returns {*} Returns the resolved value.\n */\n function baseWrapperValue(value, actions) {\n var result = value;\n if (result instanceof LazyWrapper) {\n result = result.value();\n }\n return arrayReduce(actions, function(result, action) {\n return action.func.apply(action.thisArg, arrayPush([result], action.args));\n }, result);\n }\n\n /**\n * The base implementation of methods like `_.xor`, without support for\n * iteratee shorthands, that accepts an array of arrays to inspect.\n *\n * @private\n * @param {Array} arrays The arrays to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of values.\n */\n function baseXor(arrays, iteratee, comparator) {\n var length = arrays.length;\n if (length < 2) {\n return length ? baseUniq(arrays[0]) : [];\n }\n var index = -1,\n result = Array(length);\n\n while (++index < length) {\n var array = arrays[index],\n othIndex = -1;\n\n while (++othIndex < length) {\n if (othIndex != index) {\n result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);\n }\n }\n }\n return baseUniq(baseFlatten(result, 1), iteratee, comparator);\n }\n\n /**\n * This base implementation of `_.zipObject` which assigns values using `assignFunc`.\n *\n * @private\n * @param {Array} props The property identifiers.\n * @param {Array} values The property values.\n * @param {Function} assignFunc The function to assign values.\n * @returns {Object} Returns the new object.\n */\n function baseZipObject(props, values, assignFunc) {\n var index = -1,\n length = props.length,\n valsLength = values.length,\n result = {};\n\n while (++index < length) {\n var value = index < valsLength ? values[index] : undefined;\n assignFunc(result, props[index], value);\n }\n return result;\n }\n\n /**\n * Casts `value` to an empty array if it's not an array like object.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Array|Object} Returns the cast array-like object.\n */\n function castArrayLikeObject(value) {\n return isArrayLikeObject(value) ? value : [];\n }\n\n /**\n * Casts `value` to `identity` if it's not a function.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {Function} Returns cast function.\n */\n function castFunction(value) {\n return typeof value == 'function' ? value : identity;\n }\n\n /**\n * Casts `value` to a path array if it's not one.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {Object} [object] The object to query keys on.\n * @returns {Array} Returns the cast property path array.\n */\n function castPath(value, object) {\n if (isArray(value)) {\n return value;\n }\n return isKey(value, object) ? [value] : stringToPath(toString(value));\n }\n\n /**\n * A `baseRest` alias which can be replaced with `identity` by module\n * replacement plugins.\n *\n * @private\n * @type {Function}\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n var castRest = baseRest;\n\n /**\n * Casts `array` to a slice if it's needed.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {number} start The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the cast slice.\n */\n function castSlice(array, start, end) {\n var length = array.length;\n end = end === undefined ? length : end;\n return (!start && end >= length) ? array : baseSlice(array, start, end);\n }\n\n /**\n * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).\n *\n * @private\n * @param {number|Object} id The timer id or timeout object of the timer to clear.\n */\n var clearTimeout = ctxClearTimeout || function(id) {\n return root.clearTimeout(id);\n };\n\n /**\n * Creates a clone of `buffer`.\n *\n * @private\n * @param {Buffer} buffer The buffer to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Buffer} Returns the cloned buffer.\n */\n function cloneBuffer(buffer, isDeep) {\n if (isDeep) {\n return buffer.slice();\n }\n var length = buffer.length,\n result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);\n\n buffer.copy(result);\n return result;\n }\n\n /**\n * Creates a clone of `arrayBuffer`.\n *\n * @private\n * @param {ArrayBuffer} arrayBuffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\n function cloneArrayBuffer(arrayBuffer) {\n var result = new arrayBuffer.constructor(arrayBuffer.byteLength);\n new Uint8Array(result).set(new Uint8Array(arrayBuffer));\n return result;\n }\n\n /**\n * Creates a clone of `dataView`.\n *\n * @private\n * @param {Object} dataView The data view to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned data view.\n */\n function cloneDataView(dataView, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;\n return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);\n }\n\n /**\n * Creates a clone of `regexp`.\n *\n * @private\n * @param {Object} regexp The regexp to clone.\n * @returns {Object} Returns the cloned regexp.\n */\n function cloneRegExp(regexp) {\n var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));\n result.lastIndex = regexp.lastIndex;\n return result;\n }\n\n /**\n * Creates a clone of the `symbol` object.\n *\n * @private\n * @param {Object} symbol The symbol object to clone.\n * @returns {Object} Returns the cloned symbol object.\n */\n function cloneSymbol(symbol) {\n return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};\n }\n\n /**\n * Creates a clone of `typedArray`.\n *\n * @private\n * @param {Object} typedArray The typed array to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the cloned typed array.\n */\n function cloneTypedArray(typedArray, isDeep) {\n var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;\n return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);\n }\n\n /**\n * Compares values to sort them in ascending order.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {number} Returns the sort order indicator for `value`.\n */\n function compareAscending(value, other) {\n if (value !== other) {\n var valIsDefined = value !== undefined,\n valIsNull = value === null,\n valIsReflexive = value === value,\n valIsSymbol = isSymbol(value);\n\n var othIsDefined = other !== undefined,\n othIsNull = other === null,\n othIsReflexive = other === other,\n othIsSymbol = isSymbol(other);\n\n if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||\n (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||\n (valIsNull && othIsDefined && othIsReflexive) ||\n (!valIsDefined && othIsReflexive) ||\n !valIsReflexive) {\n return 1;\n }\n if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||\n (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||\n (othIsNull && valIsDefined && valIsReflexive) ||\n (!othIsDefined && valIsReflexive) ||\n !othIsReflexive) {\n return -1;\n }\n }\n return 0;\n }\n\n /**\n * Used by `_.orderBy` to compare multiple properties of a value to another\n * and stable sort them.\n *\n * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,\n * specify an order of \"desc\" for descending or \"asc\" for ascending sort order\n * of corresponding values.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {boolean[]|string[]} orders The order to sort by for each property.\n * @returns {number} Returns the sort order indicator for `object`.\n */\n function compareMultiple(object, other, orders) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length,\n ordersLength = orders.length;\n\n while (++index < length) {\n var result = compareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n if (index >= ordersLength) {\n return result;\n }\n var order = orders[index];\n return result * (order == 'desc' ? -1 : 1);\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n }\n\n /**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgs(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersLength = holders.length,\n leftIndex = -1,\n leftLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(leftLength + rangeLength),\n isUncurried = !isCurried;\n\n while (++leftIndex < leftLength) {\n result[leftIndex] = partials[leftIndex];\n }\n while (++argsIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[holders[argsIndex]] = args[argsIndex];\n }\n }\n while (rangeLength--) {\n result[leftIndex++] = args[argsIndex++];\n }\n return result;\n }\n\n /**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @params {boolean} [isCurried] Specify composing for a curried function.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgsRight(args, partials, holders, isCurried) {\n var argsIndex = -1,\n argsLength = args.length,\n holdersIndex = -1,\n holdersLength = holders.length,\n rightIndex = -1,\n rightLength = partials.length,\n rangeLength = nativeMax(argsLength - holdersLength, 0),\n result = Array(rangeLength + rightLength),\n isUncurried = !isCurried;\n\n while (++argsIndex < rangeLength) {\n result[argsIndex] = args[argsIndex];\n }\n var offset = argsIndex;\n while (++rightIndex < rightLength) {\n result[offset + rightIndex] = partials[rightIndex];\n }\n while (++holdersIndex < holdersLength) {\n if (isUncurried || argsIndex < argsLength) {\n result[offset + holders[holdersIndex]] = args[argsIndex++];\n }\n }\n return result;\n }\n\n /**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\n function copyArray(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n }\n\n /**\n * Copies properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Array} props The property identifiers to copy.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Function} [customizer] The function to customize copied values.\n * @returns {Object} Returns `object`.\n */\n function copyObject(source, props, object, customizer) {\n var isNew = !object;\n object || (object = {});\n\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n\n var newValue = customizer\n ? customizer(object[key], source[key], key, object, source)\n : undefined;\n\n if (newValue === undefined) {\n newValue = source[key];\n }\n if (isNew) {\n baseAssignValue(object, key, newValue);\n } else {\n assignValue(object, key, newValue);\n }\n }\n return object;\n }\n\n /**\n * Copies own symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbols(source, object) {\n return copyObject(source, getSymbols(source), object);\n }\n\n /**\n * Copies own and inherited symbols of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy symbols from.\n * @param {Object} [object={}] The object to copy symbols to.\n * @returns {Object} Returns `object`.\n */\n function copySymbolsIn(source, object) {\n return copyObject(source, getSymbolsIn(source), object);\n }\n\n /**\n * Creates a function like `_.groupBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} [initializer] The accumulator object initializer.\n * @returns {Function} Returns the new aggregator function.\n */\n function createAggregator(setter, initializer) {\n return function(collection, iteratee) {\n var func = isArray(collection) ? arrayAggregator : baseAggregator,\n accumulator = initializer ? initializer() : {};\n\n return func(collection, setter, getIteratee(iteratee, 2), accumulator);\n };\n }\n\n /**\n * Creates a function like `_.assign`.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\n function createAssigner(assigner) {\n return baseRest(function(object, sources) {\n var index = -1,\n length = sources.length,\n customizer = length > 1 ? sources[length - 1] : undefined,\n guard = length > 2 ? sources[2] : undefined;\n\n customizer = (assigner.length > 3 && typeof customizer == 'function')\n ? (length--, customizer)\n : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n customizer = length < 3 ? undefined : customizer;\n length = 1;\n }\n object = Object(object);\n while (++index < length) {\n var source = sources[index];\n if (source) {\n assigner(object, source, index, customizer);\n }\n }\n return object;\n });\n }\n\n /**\n * Creates a `baseEach` or `baseEachRight` function.\n *\n * @private\n * @param {Function} eachFunc The function to iterate over a collection.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseEach(eachFunc, fromRight) {\n return function(collection, iteratee) {\n if (collection == null) {\n return collection;\n }\n if (!isArrayLike(collection)) {\n return eachFunc(collection, iteratee);\n }\n var length = collection.length,\n index = fromRight ? length : -1,\n iterable = Object(collection);\n\n while ((fromRight ? index-- : ++index < length)) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n };\n }\n\n /**\n * Creates a base function for methods like `_.forIn` and `_.forOwn`.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new base function.\n */\n function createBaseFor(fromRight) {\n return function(object, iteratee, keysFunc) {\n var index = -1,\n iterable = Object(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[fromRight ? length : ++index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n };\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the optional `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createBind(func, bitmask, thisArg) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return fn.apply(isBind ? thisArg : this, arguments);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.lowerFirst`.\n *\n * @private\n * @param {string} methodName The name of the `String` case method to use.\n * @returns {Function} Returns the new case function.\n */\n function createCaseFirst(methodName) {\n return function(string) {\n string = toString(string);\n\n var strSymbols = hasUnicode(string)\n ? stringToArray(string)\n : undefined;\n\n var chr = strSymbols\n ? strSymbols[0]\n : string.charAt(0);\n\n var trailing = strSymbols\n ? castSlice(strSymbols, 1).join('')\n : string.slice(1);\n\n return chr[methodName]() + trailing;\n };\n }\n\n /**\n * Creates a function like `_.camelCase`.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\n function createCompounder(callback) {\n return function(string) {\n return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');\n };\n }\n\n /**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCtor(Ctor) {\n return function() {\n // Use a `switch` statement to work with class constructors. See\n // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist\n // for more details.\n var args = arguments;\n switch (args.length) {\n case 0: return new Ctor;\n case 1: return new Ctor(args[0]);\n case 2: return new Ctor(args[0], args[1]);\n case 3: return new Ctor(args[0], args[1], args[2]);\n case 4: return new Ctor(args[0], args[1], args[2], args[3]);\n case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);\n case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);\n case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);\n }\n var thisBinding = baseCreate(Ctor.prototype),\n result = Ctor.apply(thisBinding, args);\n\n // Mimic the constructor's `return` behavior.\n // See https://es5.github.io/#x13.2.2 for more details.\n return isObject(result) ? result : thisBinding;\n };\n }\n\n /**\n * Creates a function that wraps `func` to enable currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {number} arity The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCurry(func, bitmask, arity) {\n var Ctor = createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length,\n placeholder = getHolder(wrapper);\n\n while (index--) {\n args[index] = arguments[index];\n }\n var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)\n ? []\n : replaceHolders(args, placeholder);\n\n length -= holders.length;\n if (length < arity) {\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, undefined,\n args, holders, undefined, undefined, arity - length);\n }\n var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n return apply(fn, this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.find` or `_.findLast` function.\n *\n * @private\n * @param {Function} findIndexFunc The function to find the collection index.\n * @returns {Function} Returns the new find function.\n */\n function createFind(findIndexFunc) {\n return function(collection, predicate, fromIndex) {\n var iterable = Object(collection);\n if (!isArrayLike(collection)) {\n var iteratee = getIteratee(predicate, 3);\n collection = keys(collection);\n predicate = function(key) { return iteratee(iterable[key], key, iterable); };\n }\n var index = findIndexFunc(collection, predicate, fromIndex);\n return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;\n };\n }\n\n /**\n * Creates a `_.flow` or `_.flowRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new flow function.\n */\n function createFlow(fromRight) {\n return flatRest(function(funcs) {\n var length = funcs.length,\n index = length,\n prereq = LodashWrapper.prototype.thru;\n\n if (fromRight) {\n funcs.reverse();\n }\n while (index--) {\n var func = funcs[index];\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (prereq && !wrapper && getFuncName(func) == 'wrapper') {\n var wrapper = new LodashWrapper([], true);\n }\n }\n index = wrapper ? index : length;\n while (++index < length) {\n func = funcs[index];\n\n var funcName = getFuncName(func),\n data = funcName == 'wrapper' ? getData(func) : undefined;\n\n if (data && isLaziable(data[0]) &&\n data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&\n !data[4].length && data[9] == 1\n ) {\n wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);\n } else {\n wrapper = (func.length == 1 && isLaziable(func))\n ? wrapper[funcName]()\n : wrapper.thru(func);\n }\n }\n return function() {\n var args = arguments,\n value = args[0];\n\n if (wrapper && args.length == 1 && isArray(value)) {\n return wrapper.plant(value).value();\n }\n var index = 0,\n result = length ? funcs[index].apply(this, args) : value;\n\n while (++index < length) {\n result = funcs[index].call(this, result);\n }\n return result;\n };\n });\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with optional `this`\n * binding of `thisArg`, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided\n * to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n var isAry = bitmask & WRAP_ARY_FLAG,\n isBind = bitmask & WRAP_BIND_FLAG,\n isBindKey = bitmask & WRAP_BIND_KEY_FLAG,\n isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),\n isFlip = bitmask & WRAP_FLIP_FLAG,\n Ctor = isBindKey ? undefined : createCtor(func);\n\n function wrapper() {\n var length = arguments.length,\n args = Array(length),\n index = length;\n\n while (index--) {\n args[index] = arguments[index];\n }\n if (isCurried) {\n var placeholder = getHolder(wrapper),\n holdersCount = countHolders(args, placeholder);\n }\n if (partials) {\n args = composeArgs(args, partials, holders, isCurried);\n }\n if (partialsRight) {\n args = composeArgsRight(args, partialsRight, holdersRight, isCurried);\n }\n length -= holdersCount;\n if (isCurried && length < arity) {\n var newHolders = replaceHolders(args, placeholder);\n return createRecurry(\n func, bitmask, createHybrid, wrapper.placeholder, thisArg,\n args, newHolders, argPos, ary, arity - length\n );\n }\n var thisBinding = isBind ? thisArg : this,\n fn = isBindKey ? thisBinding[func] : func;\n\n length = args.length;\n if (argPos) {\n args = reorder(args, argPos);\n } else if (isFlip && length > 1) {\n args.reverse();\n }\n if (isAry && ary < length) {\n args.length = ary;\n }\n if (this && this !== root && this instanceof wrapper) {\n fn = Ctor || createCtor(fn);\n }\n return fn.apply(thisBinding, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a function like `_.invertBy`.\n *\n * @private\n * @param {Function} setter The function to set accumulator values.\n * @param {Function} toIteratee The function to resolve iteratees.\n * @returns {Function} Returns the new inverter function.\n */\n function createInverter(setter, toIteratee) {\n return function(object, iteratee) {\n return baseInverter(object, setter, toIteratee(iteratee), {});\n };\n }\n\n /**\n * Creates a function that performs a mathematical operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @param {number} [defaultValue] The value used for `undefined` arguments.\n * @returns {Function} Returns the new mathematical operation function.\n */\n function createMathOperation(operator, defaultValue) {\n return function(value, other) {\n var result;\n if (value === undefined && other === undefined) {\n return defaultValue;\n }\n if (value !== undefined) {\n result = value;\n }\n if (other !== undefined) {\n if (result === undefined) {\n return other;\n }\n if (typeof value == 'string' || typeof other == 'string') {\n value = baseToString(value);\n other = baseToString(other);\n } else {\n value = baseToNumber(value);\n other = baseToNumber(other);\n }\n result = operator(value, other);\n }\n return result;\n };\n }\n\n /**\n * Creates a function like `_.over`.\n *\n * @private\n * @param {Function} arrayFunc The function to iterate over iteratees.\n * @returns {Function} Returns the new over function.\n */\n function createOver(arrayFunc) {\n return flatRest(function(iteratees) {\n iteratees = arrayMap(iteratees, baseUnary(getIteratee()));\n return baseRest(function(args) {\n var thisArg = this;\n return arrayFunc(iteratees, function(iteratee) {\n return apply(iteratee, thisArg, args);\n });\n });\n });\n }\n\n /**\n * Creates the padding for `string` based on `length`. The `chars` string\n * is truncated if the number of characters exceeds `length`.\n *\n * @private\n * @param {number} length The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padding for `string`.\n */\n function createPadding(length, chars) {\n chars = chars === undefined ? ' ' : baseToString(chars);\n\n var charsLength = chars.length;\n if (charsLength < 2) {\n return charsLength ? baseRepeat(chars, length) : chars;\n }\n var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));\n return hasUnicode(chars)\n ? castSlice(stringToArray(result), 0, length).join('')\n : result.slice(0, length);\n }\n\n /**\n * Creates a function that wraps `func` to invoke it with the `this` binding\n * of `thisArg` and `partials` prepended to the arguments it receives.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to\n * the new function.\n * @returns {Function} Returns the new wrapped function.\n */\n function createPartial(func, bitmask, thisArg, partials) {\n var isBind = bitmask & WRAP_BIND_FLAG,\n Ctor = createCtor(func);\n\n function wrapper() {\n var argsIndex = -1,\n argsLength = arguments.length,\n leftIndex = -1,\n leftLength = partials.length,\n args = Array(leftLength + argsLength),\n fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;\n\n while (++leftIndex < leftLength) {\n args[leftIndex] = partials[leftIndex];\n }\n while (argsLength--) {\n args[leftIndex++] = arguments[++argsIndex];\n }\n return apply(fn, isBind ? thisArg : this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a `_.range` or `_.rangeRight` function.\n *\n * @private\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {Function} Returns the new range function.\n */\n function createRange(fromRight) {\n return function(start, end, step) {\n if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {\n end = step = undefined;\n }\n // Ensure the sign of `-0` is preserved.\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);\n return baseRange(start, end, step, fromRight);\n };\n }\n\n /**\n * Creates a function that performs a relational operation on two values.\n *\n * @private\n * @param {Function} operator The function to perform the operation.\n * @returns {Function} Returns the new relational operation function.\n */\n function createRelationalOperation(operator) {\n return function(value, other) {\n if (!(typeof value == 'string' && typeof other == 'string')) {\n value = toNumber(value);\n other = toNumber(other);\n }\n return operator(value, other);\n };\n }\n\n /**\n * Creates a function that wraps `func` to continue currying.\n *\n * @private\n * @param {Function} func The function to wrap.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @param {Function} wrapFunc The function to create the `func` wrapper.\n * @param {*} placeholder The placeholder value.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to\n * the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {\n var isCurry = bitmask & WRAP_CURRY_FLAG,\n newHolders = isCurry ? holders : undefined,\n newHoldersRight = isCurry ? undefined : holders,\n newPartials = isCurry ? partials : undefined,\n newPartialsRight = isCurry ? undefined : partials;\n\n bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);\n bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);\n\n if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {\n bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);\n }\n var newData = [\n func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,\n newHoldersRight, argPos, ary, arity\n ];\n\n var result = wrapFunc.apply(undefined, newData);\n if (isLaziable(func)) {\n setData(result, newData);\n }\n result.placeholder = placeholder;\n return setWrapToString(result, func, bitmask);\n }\n\n /**\n * Creates a function like `_.round`.\n *\n * @private\n * @param {string} methodName The name of the `Math` method to use when rounding.\n * @returns {Function} Returns the new round function.\n */\n function createRound(methodName) {\n var func = Math[methodName];\n return function(number, precision) {\n number = toNumber(number);\n precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);\n if (precision && nativeIsFinite(number)) {\n // Shift with exponential notation to avoid floating-point issues.\n // See [MDN](https://mdn.io/round#Examples) for more details.\n var pair = (toString(number) + 'e').split('e'),\n value = func(pair[0] + 'e' + (+pair[1] + precision));\n\n pair = (toString(value) + 'e').split('e');\n return +(pair[0] + 'e' + (+pair[1] - precision));\n }\n return func(number);\n };\n }\n\n /**\n * Creates a set object of `values`.\n *\n * @private\n * @param {Array} values The values to add to the set.\n * @returns {Object} Returns the new set.\n */\n var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {\n return new Set(values);\n };\n\n /**\n * Creates a `_.toPairs` or `_.toPairsIn` function.\n *\n * @private\n * @param {Function} keysFunc The function to get the keys of a given object.\n * @returns {Function} Returns the new pairs function.\n */\n function createToPairs(keysFunc) {\n return function(object) {\n var tag = getTag(object);\n if (tag == mapTag) {\n return mapToArray(object);\n }\n if (tag == setTag) {\n return setToPairs(object);\n }\n return baseToPairs(object, keysFunc(object));\n };\n }\n\n /**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to wrap.\n * @param {number} bitmask The bitmask flags.\n * 1 - `_.bind`\n * 2 - `_.bindKey`\n * 4 - `_.curry` or `_.curryRight` of a bound function\n * 8 - `_.curry`\n * 16 - `_.curryRight`\n * 32 - `_.partial`\n * 64 - `_.partialRight`\n * 128 - `_.rearg`\n * 256 - `_.ary`\n * 512 - `_.flip`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;\n if (!isBindKey && typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var length = partials ? partials.length : 0;\n if (!length) {\n bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);\n partials = holders = undefined;\n }\n ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);\n arity = arity === undefined ? arity : toInteger(arity);\n length -= holders ? holders.length : 0;\n\n if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {\n var partialsRight = partials,\n holdersRight = holders;\n\n partials = holders = undefined;\n }\n var data = isBindKey ? undefined : getData(func);\n\n var newData = [\n func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,\n argPos, ary, arity\n ];\n\n if (data) {\n mergeData(newData, data);\n }\n func = newData[0];\n bitmask = newData[1];\n thisArg = newData[2];\n partials = newData[3];\n holders = newData[4];\n arity = newData[9] = newData[9] === undefined\n ? (isBindKey ? 0 : func.length)\n : nativeMax(newData[9] - length, 0);\n\n if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {\n bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);\n }\n if (!bitmask || bitmask == WRAP_BIND_FLAG) {\n var result = createBind(func, bitmask, thisArg);\n } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {\n result = createCurry(func, bitmask, arity);\n } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {\n result = createPartial(func, bitmask, thisArg, partials);\n } else {\n result = createHybrid.apply(undefined, newData);\n }\n var setter = data ? baseSetData : setData;\n return setWrapToString(setter(result, newData), func, bitmask);\n }\n\n /**\n * Used by `_.defaults` to customize its `_.assignIn` use to assign properties\n * of source objects to the destination object for all destination properties\n * that resolve to `undefined`.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to assign.\n * @param {Object} object The parent object of `objValue`.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsAssignIn(objValue, srcValue, key, object) {\n if (objValue === undefined ||\n (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n return srcValue;\n }\n return objValue;\n }\n\n /**\n * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source\n * objects into destination objects that are passed thru.\n *\n * @private\n * @param {*} objValue The destination value.\n * @param {*} srcValue The source value.\n * @param {string} key The key of the property to merge.\n * @param {Object} object The parent object of `objValue`.\n * @param {Object} source The parent object of `srcValue`.\n * @param {Object} [stack] Tracks traversed source values and their merged\n * counterparts.\n * @returns {*} Returns the value to assign.\n */\n function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {\n if (isObject(objValue) && isObject(srcValue)) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n stack.set(srcValue, objValue);\n baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);\n stack['delete'](srcValue);\n }\n return objValue;\n }\n\n /**\n * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain\n * objects.\n *\n * @private\n * @param {*} value The value to inspect.\n * @param {string} key The key of the property to inspect.\n * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.\n */\n function customOmitClone(value) {\n return isPlainObject(value) ? undefined : value;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `array` and `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\n function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n arrLength = array.length,\n othLength = other.length;\n\n if (arrLength != othLength && !(isPartial && othLength > arrLength)) {\n return false;\n }\n // Check that cyclic values are equal.\n var arrStacked = stack.get(array);\n var othStacked = stack.get(other);\n if (arrStacked && othStacked) {\n return arrStacked == other && othStacked == array;\n }\n var index = -1,\n result = true,\n seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;\n\n stack.set(array, other);\n stack.set(other, array);\n\n // Ignore non-index properties.\n while (++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, arrValue, index, other, array, stack)\n : customizer(arrValue, othValue, index, array, other, stack);\n }\n if (compared !== undefined) {\n if (compared) {\n continue;\n }\n result = false;\n break;\n }\n // Recursively compare arrays (susceptible to call stack limits).\n if (seen) {\n if (!arraySome(other, function(othValue, othIndex) {\n if (!cacheHas(seen, othIndex) &&\n (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {\n return seen.push(othIndex);\n }\n })) {\n result = false;\n break;\n }\n } else if (!(\n arrValue === othValue ||\n equalFunc(arrValue, othValue, bitmask, customizer, stack)\n )) {\n result = false;\n break;\n }\n }\n stack['delete'](array);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {\n switch (tag) {\n case dataViewTag:\n if ((object.byteLength != other.byteLength) ||\n (object.byteOffset != other.byteOffset)) {\n return false;\n }\n object = object.buffer;\n other = other.buffer;\n\n case arrayBufferTag:\n if ((object.byteLength != other.byteLength) ||\n !equalFunc(new Uint8Array(object), new Uint8Array(other))) {\n return false;\n }\n return true;\n\n case boolTag:\n case dateTag:\n case numberTag:\n // Coerce booleans to `1` or `0` and dates to milliseconds.\n // Invalid dates are coerced to `NaN`.\n return eq(+object, +other);\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings, primitives and objects,\n // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring\n // for more details.\n return object == (other + '');\n\n case mapTag:\n var convert = mapToArray;\n\n case setTag:\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG;\n convert || (convert = setToArray);\n\n if (object.size != other.size && !isPartial) {\n return false;\n }\n // Assume cyclic values are equal.\n var stacked = stack.get(object);\n if (stacked) {\n return stacked == other;\n }\n bitmask |= COMPARE_UNORDERED_FLAG;\n\n // Recursively compare objects (susceptible to call stack limits).\n stack.set(object, other);\n var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);\n stack['delete'](object);\n return result;\n\n case symbolTag:\n if (symbolValueOf) {\n return symbolValueOf.call(object) == symbolValueOf.call(other);\n }\n }\n return false;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.\n * @param {Function} customizer The function to customize comparisons.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Object} stack Tracks traversed `object` and `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {\n var isPartial = bitmask & COMPARE_PARTIAL_FLAG,\n objProps = getAllKeys(object),\n objLength = objProps.length,\n othProps = getAllKeys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isPartial) {\n return false;\n }\n var index = objLength;\n while (index--) {\n var key = objProps[index];\n if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {\n return false;\n }\n }\n // Check that cyclic values are equal.\n var objStacked = stack.get(object);\n var othStacked = stack.get(other);\n if (objStacked && othStacked) {\n return objStacked == other && othStacked == object;\n }\n var result = true;\n stack.set(object, other);\n stack.set(other, object);\n\n var skipCtor = isPartial;\n while (++index < objLength) {\n key = objProps[index];\n var objValue = object[key],\n othValue = other[key];\n\n if (customizer) {\n var compared = isPartial\n ? customizer(othValue, objValue, key, other, object, stack)\n : customizer(objValue, othValue, key, object, other, stack);\n }\n // Recursively compare objects (susceptible to call stack limits).\n if (!(compared === undefined\n ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))\n : compared\n )) {\n result = false;\n break;\n }\n skipCtor || (skipCtor = key == 'constructor');\n }\n if (result && !skipCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor &&\n ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor &&\n typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n result = false;\n }\n }\n stack['delete'](object);\n stack['delete'](other);\n return result;\n }\n\n /**\n * A specialized version of `baseRest` which flattens the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @returns {Function} Returns the new function.\n */\n function flatRest(func) {\n return setToString(overRest(func, undefined, flatten), func + '');\n }\n\n /**\n * Creates an array of own enumerable property names and symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeys(object) {\n return baseGetAllKeys(object, keys, getSymbols);\n }\n\n /**\n * Creates an array of own and inherited enumerable property names and\n * symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names and symbols.\n */\n function getAllKeysIn(object) {\n return baseGetAllKeys(object, keysIn, getSymbolsIn);\n }\n\n /**\n * Gets metadata for `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {*} Returns the metadata for `func`.\n */\n var getData = !metaMap ? noop : function(func) {\n return metaMap.get(func);\n };\n\n /**\n * Gets the name of `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {string} Returns the function name.\n */\n function getFuncName(func) {\n var result = (func.name + ''),\n array = realNames[result],\n length = hasOwnProperty.call(realNames, result) ? array.length : 0;\n\n while (length--) {\n var data = array[length],\n otherFunc = data.func;\n if (otherFunc == null || otherFunc == func) {\n return data.name;\n }\n }\n return result;\n }\n\n /**\n * Gets the argument placeholder value for `func`.\n *\n * @private\n * @param {Function} func The function to inspect.\n * @returns {*} Returns the placeholder value.\n */\n function getHolder(func) {\n var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;\n return object.placeholder;\n }\n\n /**\n * Gets the appropriate \"iteratee\" function. If `_.iteratee` is customized,\n * this function returns the custom method, otherwise it returns `baseIteratee`.\n * If arguments are provided, the chosen function is invoked with them and\n * its result is returned.\n *\n * @private\n * @param {*} [value] The value to convert to an iteratee.\n * @param {number} [arity] The arity of the created iteratee.\n * @returns {Function} Returns the chosen function or its result.\n */\n function getIteratee() {\n var result = lodash.iteratee || iteratee;\n result = result === iteratee ? baseIteratee : result;\n return arguments.length ? result(arguments[0], arguments[1]) : result;\n }\n\n /**\n * Gets the data for `map`.\n *\n * @private\n * @param {Object} map The map to query.\n * @param {string} key The reference key.\n * @returns {*} Returns the map data.\n */\n function getMapData(map, key) {\n var data = map.__data__;\n return isKeyable(key)\n ? data[typeof key == 'string' ? 'string' : 'hash']\n : data.map;\n }\n\n /**\n * Gets the property names, values, and compare flags of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the match data of `object`.\n */\n function getMatchData(object) {\n var result = keys(object),\n length = result.length;\n\n while (length--) {\n var key = result[length],\n value = object[key];\n\n result[length] = [key, value, isStrictComparable(value)];\n }\n return result;\n }\n\n /**\n * Gets the native function at `key` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the method to get.\n * @returns {*} Returns the function if it's native, else `undefined`.\n */\n function getNative(object, key) {\n var value = getValue(object, key);\n return baseIsNative(value) ? value : undefined;\n }\n\n /**\n * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the raw `toStringTag`.\n */\n function getRawTag(value) {\n var isOwn = hasOwnProperty.call(value, symToStringTag),\n tag = value[symToStringTag];\n\n try {\n value[symToStringTag] = undefined;\n var unmasked = true;\n } catch (e) {}\n\n var result = nativeObjectToString.call(value);\n if (unmasked) {\n if (isOwn) {\n value[symToStringTag] = tag;\n } else {\n delete value[symToStringTag];\n }\n }\n return result;\n }\n\n /**\n * Creates an array of the own enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbols = !nativeGetSymbols ? stubArray : function(object) {\n if (object == null) {\n return [];\n }\n object = Object(object);\n return arrayFilter(nativeGetSymbols(object), function(symbol) {\n return propertyIsEnumerable.call(object, symbol);\n });\n };\n\n /**\n * Creates an array of the own and inherited enumerable symbols of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of symbols.\n */\n var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {\n var result = [];\n while (object) {\n arrayPush(result, getSymbols(object));\n object = getPrototype(object);\n }\n return result;\n };\n\n /**\n * Gets the `toStringTag` of `value`.\n *\n * @private\n * @param {*} value The value to query.\n * @returns {string} Returns the `toStringTag`.\n */\n var getTag = baseGetTag;\n\n // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.\n if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||\n (Map && getTag(new Map) != mapTag) ||\n (Promise && getTag(Promise.resolve()) != promiseTag) ||\n (Set && getTag(new Set) != setTag) ||\n (WeakMap && getTag(new WeakMap) != weakMapTag)) {\n getTag = function(value) {\n var result = baseGetTag(value),\n Ctor = result == objectTag ? value.constructor : undefined,\n ctorString = Ctor ? toSource(Ctor) : '';\n\n if (ctorString) {\n switch (ctorString) {\n case dataViewCtorString: return dataViewTag;\n case mapCtorString: return mapTag;\n case promiseCtorString: return promiseTag;\n case setCtorString: return setTag;\n case weakMapCtorString: return weakMapTag;\n }\n }\n return result;\n };\n }\n\n /**\n * Gets the view, applying any `transforms` to the `start` and `end` positions.\n *\n * @private\n * @param {number} start The start of the view.\n * @param {number} end The end of the view.\n * @param {Array} transforms The transformations to apply to the view.\n * @returns {Object} Returns an object containing the `start` and `end`\n * positions of the view.\n */\n function getView(start, end, transforms) {\n var index = -1,\n length = transforms.length;\n\n while (++index < length) {\n var data = transforms[index],\n size = data.size;\n\n switch (data.type) {\n case 'drop': start += size; break;\n case 'dropRight': end -= size; break;\n case 'take': end = nativeMin(end, start + size); break;\n case 'takeRight': start = nativeMax(start, end - size); break;\n }\n }\n return { 'start': start, 'end': end };\n }\n\n /**\n * Extracts wrapper details from the `source` body comment.\n *\n * @private\n * @param {string} source The source to inspect.\n * @returns {Array} Returns the wrapper details.\n */\n function getWrapDetails(source) {\n var match = source.match(reWrapDetails);\n return match ? match[1].split(reSplitDetails) : [];\n }\n\n /**\n * Checks if `path` exists on `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @param {Function} hasFunc The function to check properties.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n */\n function hasPath(object, path, hasFunc) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length,\n result = false;\n\n while (++index < length) {\n var key = toKey(path[index]);\n if (!(result = object != null && hasFunc(object, key))) {\n break;\n }\n object = object[key];\n }\n if (result || ++index != length) {\n return result;\n }\n length = object == null ? 0 : object.length;\n return !!length && isLength(length) && isIndex(key, length) &&\n (isArray(object) || isArguments(object));\n }\n\n /**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\n function initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n }\n\n /**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneObject(object) {\n return (typeof object.constructor == 'function' && !isPrototype(object))\n ? baseCreate(getPrototype(object))\n : {};\n }\n\n /**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return cloneArrayBuffer(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case dataViewTag:\n return cloneDataView(object, isDeep);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n return cloneTypedArray(object, isDeep);\n\n case mapTag:\n return new Ctor;\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n return cloneRegExp(object);\n\n case setTag:\n return new Ctor;\n\n case symbolTag:\n return cloneSymbol(object);\n }\n }\n\n /**\n * Inserts wrapper `details` in a comment at the top of the `source` body.\n *\n * @private\n * @param {string} source The source to modify.\n * @returns {Array} details The details to insert.\n * @returns {string} Returns the modified source.\n */\n function insertWrapDetails(source, details) {\n var length = details.length;\n if (!length) {\n return source;\n }\n var lastIndex = length - 1;\n details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];\n details = details.join(length > 2 ? ', ' : ' ');\n return source.replace(reWrapComment, '{\\n/* [wrapped with ' + details + '] */\\n');\n }\n\n /**\n * Checks if `value` is a flattenable `arguments` object or array.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.\n */\n function isFlattenable(value) {\n return isArray(value) || isArguments(value) ||\n !!(spreadableSymbol && value && value[spreadableSymbol]);\n }\n\n /**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\n function isIndex(value, length) {\n var type = typeof value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n\n return !!length &&\n (type == 'number' ||\n (type != 'symbol' && reIsUint.test(value))) &&\n (value > -1 && value % 1 == 0 && value < length);\n }\n\n /**\n * Checks if the given arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call,\n * else `false`.\n */\n function isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number'\n ? (isArrayLike(object) && isIndex(index, object.length))\n : (type == 'string' && index in object)\n ) {\n return eq(object[index], value);\n }\n return false;\n }\n\n /**\n * Checks if `value` is a property name and not a property path.\n *\n * @private\n * @param {*} value The value to check.\n * @param {Object} [object] The object to query keys on.\n * @returns {boolean} Returns `true` if `value` is a property name, else `false`.\n */\n function isKey(value, object) {\n if (isArray(value)) {\n return false;\n }\n var type = typeof value;\n if (type == 'number' || type == 'symbol' || type == 'boolean' ||\n value == null || isSymbol(value)) {\n return true;\n }\n return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||\n (object != null && value in Object(object));\n }\n\n /**\n * Checks if `value` is suitable for use as unique object key.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is suitable, else `false`.\n */\n function isKeyable(value) {\n var type = typeof value;\n return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')\n ? (value !== '__proto__')\n : (value === null);\n }\n\n /**\n * Checks if `func` has a lazy counterpart.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` has a lazy counterpart,\n * else `false`.\n */\n function isLaziable(func) {\n var funcName = getFuncName(func),\n other = lodash[funcName];\n\n if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {\n return false;\n }\n if (func === other) {\n return true;\n }\n var data = getData(other);\n return !!data && func === data[0];\n }\n\n /**\n * Checks if `func` has its source masked.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is masked, else `false`.\n */\n function isMasked(func) {\n return !!maskSrcKey && (maskSrcKey in func);\n }\n\n /**\n * Checks if `func` is capable of being masked.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `func` is maskable, else `false`.\n */\n var isMaskable = coreJsData ? isFunction : stubFalse;\n\n /**\n * Checks if `value` is likely a prototype object.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.\n */\n function isPrototype(value) {\n var Ctor = value && value.constructor,\n proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;\n\n return value === proto;\n }\n\n /**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\n function isStrictComparable(value) {\n return value === value && !isObject(value);\n }\n\n /**\n * A specialized version of `matchesProperty` for source values suitable\n * for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} srcValue The value to match.\n * @returns {Function} Returns the new spec function.\n */\n function matchesStrictComparable(key, srcValue) {\n return function(object) {\n if (object == null) {\n return false;\n }\n return object[key] === srcValue &&\n (srcValue !== undefined || (key in Object(object)));\n };\n }\n\n /**\n * A specialized version of `_.memoize` which clears the memoized function's\n * cache when it exceeds `MAX_MEMOIZE_SIZE`.\n *\n * @private\n * @param {Function} func The function to have its output memoized.\n * @returns {Function} Returns the new memoized function.\n */\n function memoizeCapped(func) {\n var result = memoize(func, function(key) {\n if (cache.size === MAX_MEMOIZE_SIZE) {\n cache.clear();\n }\n return key;\n });\n\n var cache = result.cache;\n return result;\n }\n\n /**\n * Merges the function metadata of `source` into `data`.\n *\n * Merging metadata reduces the number of wrappers used to invoke a function.\n * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n * may be applied regardless of execution order. Methods like `_.ary` and\n * `_.rearg` modify function arguments, making the order in which they are\n * executed important, preventing the merging of metadata. However, we make\n * an exception for a safe combined case where curried functions have `_.ary`\n * and or `_.rearg` applied.\n *\n * @private\n * @param {Array} data The destination metadata.\n * @param {Array} source The source metadata.\n * @returns {Array} Returns `data`.\n */\n function mergeData(data, source) {\n var bitmask = data[1],\n srcBitmask = source[1],\n newBitmask = bitmask | srcBitmask,\n isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);\n\n var isCombo =\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||\n ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||\n ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));\n\n // Exit early if metadata can't be merged.\n if (!(isCommon || isCombo)) {\n return data;\n }\n // Use source `thisArg` if available.\n if (srcBitmask & WRAP_BIND_FLAG) {\n data[2] = source[2];\n // Set when currying a bound function.\n newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;\n }\n // Compose partial arguments.\n var value = source[3];\n if (value) {\n var partials = data[3];\n data[3] = partials ? composeArgs(partials, value, source[4]) : value;\n data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];\n }\n // Compose partial right arguments.\n value = source[5];\n if (value) {\n partials = data[5];\n data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;\n data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];\n }\n // Use source `argPos` if available.\n value = source[7];\n if (value) {\n data[7] = value;\n }\n // Use source `ary` if it's smaller.\n if (srcBitmask & WRAP_ARY_FLAG) {\n data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n }\n // Use source `arity` if one is not provided.\n if (data[9] == null) {\n data[9] = source[9];\n }\n // Use source `func` and merge bitmasks.\n data[0] = source[0];\n data[1] = newBitmask;\n\n return data;\n }\n\n /**\n * This function is like\n * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * except that it includes inherited enumerable properties.\n *\n * @private\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n */\n function nativeKeysIn(object) {\n var result = [];\n if (object != null) {\n for (var key in Object(object)) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * Converts `value` to a string using `Object.prototype.toString`.\n *\n * @private\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n */\n function objectToString(value) {\n return nativeObjectToString.call(value);\n }\n\n /**\n * A specialized version of `baseRest` which transforms the rest array.\n *\n * @private\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @param {Function} transform The rest array transform.\n * @returns {Function} Returns the new function.\n */\n function overRest(func, start, transform) {\n start = nativeMax(start === undefined ? (func.length - 1) : start, 0);\n return function() {\n var args = arguments,\n index = -1,\n length = nativeMax(args.length - start, 0),\n array = Array(length);\n\n while (++index < length) {\n array[index] = args[start + index];\n }\n index = -1;\n var otherArgs = Array(start + 1);\n while (++index < start) {\n otherArgs[index] = args[index];\n }\n otherArgs[start] = transform(array);\n return apply(func, this, otherArgs);\n };\n }\n\n /**\n * Gets the parent value at `path` of `object`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} path The path to get the parent value of.\n * @returns {*} Returns the parent value.\n */\n function parent(object, path) {\n return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));\n }\n\n /**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\n function reorder(array, indexes) {\n var arrLength = array.length,\n length = nativeMin(indexes.length, arrLength),\n oldArray = copyArray(array);\n\n while (length--) {\n var index = indexes[length];\n array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n }\n return array;\n }\n\n /**\n * Gets the value at `key`, unless `key` is \"__proto__\" or \"constructor\".\n *\n * @private\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to get.\n * @returns {*} Returns the property value.\n */\n function safeGet(object, key) {\n if (key === 'constructor' && typeof object[key] === 'function') {\n return;\n }\n\n if (key == '__proto__') {\n return;\n }\n\n return object[key];\n }\n\n /**\n * Sets metadata for `func`.\n *\n * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n * period of time, it will trip its breaker and transition to an identity\n * function to avoid garbage collection pauses in V8. See\n * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)\n * for more details.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var setData = shortOut(baseSetData);\n\n /**\n * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @returns {number|Object} Returns the timer id or timeout object.\n */\n var setTimeout = ctxSetTimeout || function(func, wait) {\n return root.setTimeout(func, wait);\n };\n\n /**\n * Sets the `toString` method of `func` to return `string`.\n *\n * @private\n * @param {Function} func The function to modify.\n * @param {Function} string The `toString` result.\n * @returns {Function} Returns `func`.\n */\n var setToString = shortOut(baseSetToString);\n\n /**\n * Sets the `toString` method of `wrapper` to mimic the source of `reference`\n * with wrapper details in a comment at the top of the source body.\n *\n * @private\n * @param {Function} wrapper The function to modify.\n * @param {Function} reference The reference function.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Function} Returns `wrapper`.\n */\n function setWrapToString(wrapper, reference, bitmask) {\n var source = (reference + '');\n return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));\n }\n\n /**\n * Creates a function that'll short out and invoke `identity` instead\n * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`\n * milliseconds.\n *\n * @private\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new shortable function.\n */\n function shortOut(func) {\n var count = 0,\n lastCalled = 0;\n\n return function() {\n var stamp = nativeNow(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return arguments[0];\n }\n } else {\n count = 0;\n }\n return func.apply(undefined, arguments);\n };\n }\n\n /**\n * A specialized version of `_.shuffle` which mutates and sets the size of `array`.\n *\n * @private\n * @param {Array} array The array to shuffle.\n * @param {number} [size=array.length] The size of `array`.\n * @returns {Array} Returns `array`.\n */\n function shuffleSelf(array, size) {\n var index = -1,\n length = array.length,\n lastIndex = length - 1;\n\n size = size === undefined ? length : size;\n while (++index < size) {\n var rand = baseRandom(index, lastIndex),\n value = array[rand];\n\n array[rand] = array[index];\n array[index] = value;\n }\n array.length = size;\n return array;\n }\n\n /**\n * Converts `string` to a property path array.\n *\n * @private\n * @param {string} string The string to convert.\n * @returns {Array} Returns the property path array.\n */\n var stringToPath = memoizeCapped(function(string) {\n var result = [];\n if (string.charCodeAt(0) === 46 /* . */) {\n result.push('');\n }\n string.replace(rePropName, function(match, number, quote, subString) {\n result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));\n });\n return result;\n });\n\n /**\n * Converts `value` to a string key if it's not a string or symbol.\n *\n * @private\n * @param {*} value The value to inspect.\n * @returns {string|symbol} Returns the key.\n */\n function toKey(value) {\n if (typeof value == 'string' || isSymbol(value)) {\n return value;\n }\n var result = (value + '');\n return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;\n }\n\n /**\n * Converts `func` to its source code.\n *\n * @private\n * @param {Function} func The function to convert.\n * @returns {string} Returns the source code.\n */\n function toSource(func) {\n if (func != null) {\n try {\n return funcToString.call(func);\n } catch (e) {}\n try {\n return (func + '');\n } catch (e) {}\n }\n return '';\n }\n\n /**\n * Updates wrapper `details` based on `bitmask` flags.\n *\n * @private\n * @returns {Array} details The details to modify.\n * @param {number} bitmask The bitmask flags. See `createWrap` for more details.\n * @returns {Array} Returns `details`.\n */\n function updateWrapDetails(details, bitmask) {\n arrayEach(wrapFlags, function(pair) {\n var value = '_.' + pair[0];\n if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {\n details.push(value);\n }\n });\n return details.sort();\n }\n\n /**\n * Creates a clone of `wrapper`.\n *\n * @private\n * @param {Object} wrapper The wrapper to clone.\n * @returns {Object} Returns the cloned wrapper.\n */\n function wrapperClone(wrapper) {\n if (wrapper instanceof LazyWrapper) {\n return wrapper.clone();\n }\n var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);\n result.__actions__ = copyArray(wrapper.__actions__);\n result.__index__ = wrapper.__index__;\n result.__values__ = wrapper.__values__;\n return result;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of elements split into groups the length of `size`.\n * If `array` can't be split evenly, the final chunk will be the remaining\n * elements.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to process.\n * @param {number} [size=1] The length of each chunk\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the new array of chunks.\n * @example\n *\n * _.chunk(['a', 'b', 'c', 'd'], 2);\n * // => [['a', 'b'], ['c', 'd']]\n *\n * _.chunk(['a', 'b', 'c', 'd'], 3);\n * // => [['a', 'b', 'c'], ['d']]\n */\n function chunk(array, size, guard) {\n if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {\n size = 1;\n } else {\n size = nativeMax(toInteger(size), 0);\n }\n var length = array == null ? 0 : array.length;\n if (!length || size < 1) {\n return [];\n }\n var index = 0,\n resIndex = 0,\n result = Array(nativeCeil(length / size));\n\n while (index < length) {\n result[resIndex++] = baseSlice(array, index, (index += size));\n }\n return result;\n }\n\n /**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\n function compact(array) {\n var index = -1,\n length = array == null ? 0 : array.length,\n resIndex = 0,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value) {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /**\n * Creates a new array concatenating `array` with any additional arrays\n * and/or values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to concatenate.\n * @param {...*} [values] The values to concatenate.\n * @returns {Array} Returns the new concatenated array.\n * @example\n *\n * var array = [1];\n * var other = _.concat(array, 2, [3], [[4]]);\n *\n * console.log(other);\n * // => [1, 2, 3, [4]]\n *\n * console.log(array);\n * // => [1]\n */\n function concat() {\n var length = arguments.length;\n if (!length) {\n return [];\n }\n var args = Array(length - 1),\n array = arguments[0],\n index = length;\n\n while (index--) {\n args[index - 1] = arguments[index];\n }\n return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));\n }\n\n /**\n * Creates an array of `array` values not included in the other given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * **Note:** Unlike `_.pullAll`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.without, _.xor\n * @example\n *\n * _.difference([2, 1], [2, 3]);\n * // => [1]\n */\n var difference = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `iteratee` which\n * is invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * **Note:** Unlike `_.pullAllBy`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var differenceBy = baseRest(function(array, values) {\n var iteratee = last(values);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.difference` except that it accepts `comparator`\n * which is invoked to compare elements of `array` to `values`. The order and\n * references of result values are determined by the first array. The comparator\n * is invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.pullAllWith`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The values to exclude.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n *\n * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }]\n */\n var differenceWith = baseRest(function(array, values) {\n var comparator = last(values);\n if (isArrayLikeObject(comparator)) {\n comparator = undefined;\n }\n return isArrayLikeObject(array)\n ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)\n : [];\n });\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.drop([1, 2, 3]);\n * // => [2, 3]\n *\n * _.drop([1, 2, 3], 2);\n * // => [3]\n *\n * _.drop([1, 2, 3], 5);\n * // => []\n *\n * _.drop([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function drop(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRight([1, 2, 3]);\n * // => [1, 2]\n *\n * _.dropRight([1, 2, 3], 2);\n * // => [1]\n *\n * _.dropRight([1, 2, 3], 5);\n * // => []\n *\n * _.dropRight([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function dropRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the end.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.dropRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropRightWhile(users, ['active', false]);\n * // => objects for ['barney']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropRightWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the beginning.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.dropWhile(users, function(o) { return !o.active; });\n * // => objects for ['pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.dropWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.dropWhile(users, ['active', false]);\n * // => objects for ['pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.dropWhile(users, 'active');\n * // => objects for ['barney', 'fred', 'pebbles']\n */\n function dropWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), true)\n : [];\n }\n\n /**\n * Fills elements of `array` with `value` from `start` up to, but not\n * including, `end`.\n *\n * **Note:** This method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Array\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.fill(array, 'a');\n * console.log(array);\n * // => ['a', 'a', 'a']\n *\n * _.fill(Array(3), 2);\n * // => [2, 2, 2]\n *\n * _.fill([4, 6, 8, 10], '*', 1, 3);\n * // => [4, '*', '*', 10]\n */\n function fill(array, value, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {\n start = 0;\n end = length;\n }\n return baseFill(array, value, start, end);\n }\n\n /**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(o) { return o.user == 'barney'; });\n * // => 0\n *\n * // The `_.matches` iteratee shorthand.\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findIndex(users, ['active', false]);\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.findIndex(users, 'active');\n * // => 2\n */\n function findIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index);\n }\n\n /**\n * This method is like `_.findIndex` except that it iterates over elements\n * of `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });\n * // => 2\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastIndex(users, { 'user': 'barney', 'active': true });\n * // => 0\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastIndex(users, ['active', false]);\n * // => 2\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastIndex(users, 'active');\n * // => 0\n */\n function findLastIndex(array, predicate, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length - 1;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = fromIndex < 0\n ? nativeMax(length + index, 0)\n : nativeMin(index, length - 1);\n }\n return baseFindIndex(array, getIteratee(predicate, 3), index, true);\n }\n\n /**\n * Flattens `array` a single level deep.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, [3, [4]], 5]]);\n * // => [1, 2, [3, [4]], 5]\n */\n function flatten(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, 1) : [];\n }\n\n /**\n * Recursively flattens `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flattenDeep([1, [2, [3, [4]], 5]]);\n * // => [1, 2, 3, 4, 5]\n */\n function flattenDeep(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseFlatten(array, INFINITY) : [];\n }\n\n /**\n * Recursively flatten `array` up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Array\n * @param {Array} array The array to flatten.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * var array = [1, [2, [3, [4]], 5]];\n *\n * _.flattenDepth(array, 1);\n * // => [1, 2, [3, [4]], 5]\n *\n * _.flattenDepth(array, 2);\n * // => [1, 2, 3, [4], 5]\n */\n function flattenDepth(array, depth) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(array, depth);\n }\n\n /**\n * The inverse of `_.toPairs`; this method returns an object composed\n * from key-value `pairs`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} pairs The key-value pairs.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.fromPairs([['a', 1], ['b', 2]]);\n * // => { 'a': 1, 'b': 2 }\n */\n function fromPairs(pairs) {\n var index = -1,\n length = pairs == null ? 0 : pairs.length,\n result = {};\n\n while (++index < length) {\n var pair = pairs[index];\n result[pair[0]] = pair[1];\n }\n return result;\n }\n\n /**\n * Gets the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias first\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the first element of `array`.\n * @example\n *\n * _.head([1, 2, 3]);\n * // => 1\n *\n * _.head([]);\n * // => undefined\n */\n function head(array) {\n return (array && array.length) ? array[0] : undefined;\n }\n\n /**\n * Gets the index at which the first occurrence of `value` is found in `array`\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. If `fromIndex` is negative, it's used as the\n * offset from the end of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.indexOf([1, 2, 1, 2], 2);\n * // => 1\n *\n * // Search from the `fromIndex`.\n * _.indexOf([1, 2, 1, 2], 2, 2);\n * // => 3\n */\n function indexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = fromIndex == null ? 0 : toInteger(fromIndex);\n if (index < 0) {\n index = nativeMax(length + index, 0);\n }\n return baseIndexOf(array, value, index);\n }\n\n /**\n * Gets all but the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.initial([1, 2, 3]);\n * // => [1, 2]\n */\n function initial(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 0, -1) : [];\n }\n\n /**\n * Creates an array of unique values that are included in all given arrays\n * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons. The order and references of result values are\n * determined by the first array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersection([2, 1], [2, 3]);\n * // => [2]\n */\n var intersection = baseRest(function(arrays) {\n var mapped = arrayMap(arrays, castArrayLikeObject);\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped)\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `iteratee`\n * which is invoked for each element of each `arrays` to generate the criterion\n * by which they're compared. The order and references of result values are\n * determined by the first array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [2.1]\n *\n * // The `_.property` iteratee shorthand.\n * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }]\n */\n var intersectionBy = baseRest(function(arrays) {\n var iteratee = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n if (iteratee === last(mapped)) {\n iteratee = undefined;\n } else {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, getIteratee(iteratee, 2))\n : [];\n });\n\n /**\n * This method is like `_.intersection` except that it accepts `comparator`\n * which is invoked to compare elements of `arrays`. The order and references\n * of result values are determined by the first array. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of intersecting values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.intersectionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }]\n */\n var intersectionWith = baseRest(function(arrays) {\n var comparator = last(arrays),\n mapped = arrayMap(arrays, castArrayLikeObject);\n\n comparator = typeof comparator == 'function' ? comparator : undefined;\n if (comparator) {\n mapped.pop();\n }\n return (mapped.length && mapped[0] === arrays[0])\n ? baseIntersection(mapped, undefined, comparator)\n : [];\n });\n\n /**\n * Converts all elements in `array` into a string separated by `separator`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to convert.\n * @param {string} [separator=','] The element separator.\n * @returns {string} Returns the joined string.\n * @example\n *\n * _.join(['a', 'b', 'c'], '~');\n * // => 'a~b~c'\n */\n function join(array, separator) {\n return array == null ? '' : nativeJoin.call(array, separator);\n }\n\n /**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\n function last(array) {\n var length = array == null ? 0 : array.length;\n return length ? array[length - 1] : undefined;\n }\n\n /**\n * This method is like `_.indexOf` except that it iterates over elements of\n * `array` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=array.length-1] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.lastIndexOf([1, 2, 1, 2], 2);\n * // => 3\n *\n * // Search from the `fromIndex`.\n * _.lastIndexOf([1, 2, 1, 2], 2, 2);\n * // => 1\n */\n function lastIndexOf(array, value, fromIndex) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return -1;\n }\n var index = length;\n if (fromIndex !== undefined) {\n index = toInteger(fromIndex);\n index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);\n }\n return value === value\n ? strictLastIndexOf(array, value, index)\n : baseFindIndex(array, baseIsNaN, index, true);\n }\n\n /**\n * Gets the element at index `n` of `array`. If `n` is negative, the nth\n * element from the end is returned.\n *\n * @static\n * @memberOf _\n * @since 4.11.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=0] The index of the element to return.\n * @returns {*} Returns the nth element of `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n *\n * _.nth(array, 1);\n * // => 'b'\n *\n * _.nth(array, -2);\n * // => 'c';\n */\n function nth(array, n) {\n return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;\n }\n\n /**\n * Removes all given values from `array` using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`\n * to remove elements from an array by predicate.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...*} [values] The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pull(array, 'a', 'c');\n * console.log(array);\n * // => ['b', 'b']\n */\n var pull = baseRest(pullAll);\n\n /**\n * This method is like `_.pull` except that it accepts an array of values to remove.\n *\n * **Note:** Unlike `_.difference`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = ['a', 'b', 'c', 'a', 'b', 'c'];\n *\n * _.pullAll(array, ['a', 'c']);\n * console.log(array);\n * // => ['b', 'b']\n */\n function pullAll(array, values) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values)\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `iteratee` which is\n * invoked for each element of `array` and `values` to generate the criterion\n * by which they're compared. The iteratee is invoked with one argument: (value).\n *\n * **Note:** Unlike `_.differenceBy`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];\n *\n * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');\n * console.log(array);\n * // => [{ 'x': 2 }]\n */\n function pullAllBy(array, values, iteratee) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, getIteratee(iteratee, 2))\n : array;\n }\n\n /**\n * This method is like `_.pullAll` except that it accepts `comparator` which\n * is invoked to compare elements of `array` to `values`. The comparator is\n * invoked with two arguments: (arrVal, othVal).\n *\n * **Note:** Unlike `_.differenceWith`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Array} values The values to remove.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];\n *\n * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);\n * console.log(array);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]\n */\n function pullAllWith(array, values, comparator) {\n return (array && array.length && values && values.length)\n ? basePullAll(array, values, undefined, comparator)\n : array;\n }\n\n /**\n * Removes elements from `array` corresponding to `indexes` and returns an\n * array of removed elements.\n *\n * **Note:** Unlike `_.at`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...(number|number[])} [indexes] The indexes of elements to remove.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = ['a', 'b', 'c', 'd'];\n * var pulled = _.pullAt(array, [1, 3]);\n *\n * console.log(array);\n * // => ['a', 'c']\n *\n * console.log(pulled);\n * // => ['b', 'd']\n */\n var pullAt = flatRest(function(array, indexes) {\n var length = array == null ? 0 : array.length,\n result = baseAt(array, indexes);\n\n basePullAt(array, arrayMap(indexes, function(index) {\n return isIndex(index, length) ? +index : index;\n }).sort(compareAscending));\n\n return result;\n });\n\n /**\n * Removes all elements from `array` that `predicate` returns truthy for\n * and returns an array of the removed elements. The predicate is invoked\n * with three arguments: (value, index, array).\n *\n * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`\n * to pull elements from an array by value.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = [1, 2, 3, 4];\n * var evens = _.remove(array, function(n) {\n * return n % 2 == 0;\n * });\n *\n * console.log(array);\n * // => [1, 3]\n *\n * console.log(evens);\n * // => [2, 4]\n */\n function remove(array, predicate) {\n var result = [];\n if (!(array && array.length)) {\n return result;\n }\n var index = -1,\n indexes = [],\n length = array.length;\n\n predicate = getIteratee(predicate, 3);\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result.push(value);\n indexes.push(index);\n }\n }\n basePullAt(array, indexes);\n return result;\n }\n\n /**\n * Reverses `array` so that the first element becomes the last, the second\n * element becomes the second to last, and so on.\n *\n * **Note:** This method mutates `array` and is based on\n * [`Array#reverse`](https://mdn.io/Array/reverse).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to modify.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _.reverse(array);\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function reverse(array) {\n return array == null ? array : nativeReverse.call(array);\n }\n\n /**\n * Creates a slice of `array` from `start` up to, but not including, `end`.\n *\n * **Note:** This method is used instead of\n * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are\n * returned.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function slice(array, start, end) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {\n start = 0;\n end = length;\n }\n else {\n start = start == null ? 0 : toInteger(start);\n end = end === undefined ? length : toInteger(end);\n }\n return baseSlice(array, start, end);\n }\n\n /**\n * Uses a binary search to determine the lowest index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedIndex([30, 50], 40);\n * // => 1\n */\n function sortedIndex(array, value) {\n return baseSortedIndex(array, value);\n }\n\n /**\n * This method is like `_.sortedIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 0\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedIndexBy(objects, { 'x': 4 }, 'x');\n * // => 0\n */\n function sortedIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));\n }\n\n /**\n * This method is like `_.indexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedIndexOf([4, 5, 5, 5, 6], 5);\n * // => 1\n */\n function sortedIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value);\n if (index < length && eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.sortedIndex` except that it returns the highest\n * index at which `value` should be inserted into `array` in order to\n * maintain its sort order.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedLastIndex([4, 5, 5, 5, 6], 5);\n * // => 4\n */\n function sortedLastIndex(array, value) {\n return baseSortedIndex(array, value, true);\n }\n\n /**\n * This method is like `_.sortedLastIndex` except that it accepts `iteratee`\n * which is invoked for `value` and each element of `array` to compute their\n * sort ranking. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * var objects = [{ 'x': 4 }, { 'x': 5 }];\n *\n * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });\n * // => 1\n *\n * // The `_.property` iteratee shorthand.\n * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');\n * // => 1\n */\n function sortedLastIndexBy(array, value, iteratee) {\n return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);\n }\n\n /**\n * This method is like `_.lastIndexOf` except that it performs a binary\n * search on a sorted `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {*} value The value to search for.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);\n * // => 3\n */\n function sortedLastIndexOf(array, value) {\n var length = array == null ? 0 : array.length;\n if (length) {\n var index = baseSortedIndex(array, value, true) - 1;\n if (eq(array[index], value)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.uniq` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniq([1, 1, 2]);\n * // => [1, 2]\n */\n function sortedUniq(array) {\n return (array && array.length)\n ? baseSortedUniq(array)\n : [];\n }\n\n /**\n * This method is like `_.uniqBy` except that it's designed and optimized\n * for sorted arrays.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);\n * // => [1.1, 2.3]\n */\n function sortedUniqBy(array, iteratee) {\n return (array && array.length)\n ? baseSortedUniq(array, getIteratee(iteratee, 2))\n : [];\n }\n\n /**\n * Gets all but the first element of `array`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.tail([1, 2, 3]);\n * // => [2, 3]\n */\n function tail(array) {\n var length = array == null ? 0 : array.length;\n return length ? baseSlice(array, 1, length) : [];\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the beginning.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.take([1, 2, 3]);\n * // => [1]\n *\n * _.take([1, 2, 3], 2);\n * // => [1, 2]\n *\n * _.take([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.take([1, 2, 3], 0);\n * // => []\n */\n function take(array, n, guard) {\n if (!(array && array.length)) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the end.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeRight([1, 2, 3]);\n * // => [3]\n *\n * _.takeRight([1, 2, 3], 2);\n * // => [2, 3]\n *\n * _.takeRight([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.takeRight([1, 2, 3], 0);\n * // => []\n */\n function takeRight(array, n, guard) {\n var length = array == null ? 0 : array.length;\n if (!length) {\n return [];\n }\n n = (guard || n === undefined) ? 1 : toInteger(n);\n n = length - n;\n return baseSlice(array, n < 0 ? 0 : n, length);\n }\n\n /**\n * Creates a slice of `array` with elements taken from the end. Elements are\n * taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.takeRightWhile(users, function(o) { return !o.active; });\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });\n * // => objects for ['pebbles']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeRightWhile(users, ['active', false]);\n * // => objects for ['fred', 'pebbles']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeRightWhile(users, 'active');\n * // => []\n */\n function takeRightWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3), false, true)\n : [];\n }\n\n /**\n * Creates a slice of `array` with elements taken from the beginning. Elements\n * are taken until `predicate` returns falsey. The predicate is invoked with\n * three arguments: (value, index, array).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.takeWhile(users, function(o) { return !o.active; });\n * // => objects for ['barney', 'fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.takeWhile(users, { 'user': 'barney', 'active': false });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.takeWhile(users, ['active', false]);\n * // => objects for ['barney', 'fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.takeWhile(users, 'active');\n * // => []\n */\n function takeWhile(array, predicate) {\n return (array && array.length)\n ? baseWhile(array, getIteratee(predicate, 3))\n : [];\n }\n\n /**\n * Creates an array of unique values, in order, from all given arrays using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([2], [1, 2]);\n * // => [2, 1]\n */\n var union = baseRest(function(arrays) {\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));\n });\n\n /**\n * This method is like `_.union` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which uniqueness is computed. Result values are chosen from the first\n * array in which the value occurs. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.unionBy([2.1], [1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n var unionBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.union` except that it accepts `comparator` which\n * is invoked to compare elements of `arrays`. Result values are chosen from\n * the first array in which the value occurs. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.unionWith(objects, others, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var unionWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);\n });\n\n /**\n * Creates a duplicate-free version of an array, using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons, in which only the first occurrence of each element\n * is kept. The order of result values is determined by the order they occur\n * in the array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniq([2, 1, 2]);\n * // => [2, 1]\n */\n function uniq(array) {\n return (array && array.length) ? baseUniq(array) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `iteratee` which is\n * invoked for each element in `array` to generate the criterion by which\n * uniqueness is computed. The order of result values is determined by the\n * order they occur in the array. The iteratee is invoked with one argument:\n * (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * _.uniqBy([2.1, 1.2, 2.3], Math.floor);\n * // => [2.1, 1.2]\n *\n * // The `_.property` iteratee shorthand.\n * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n function uniqBy(array, iteratee) {\n return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];\n }\n\n /**\n * This method is like `_.uniq` except that it accepts `comparator` which\n * is invoked to compare elements of `array`. The order of result values is\n * determined by the order they occur in the array.The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new duplicate free array.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.uniqWith(objects, _.isEqual);\n * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]\n */\n function uniqWith(array, comparator) {\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return (array && array.length) ? baseUniq(array, undefined, comparator) : [];\n }\n\n /**\n * This method is like `_.zip` except that it accepts an array of grouped\n * elements and creates an array regrouping the elements to their pre-zip\n * configuration.\n *\n * @static\n * @memberOf _\n * @since 1.2.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n *\n * _.unzip(zipped);\n * // => [['a', 'b'], [1, 2], [true, false]]\n */\n function unzip(array) {\n if (!(array && array.length)) {\n return [];\n }\n var length = 0;\n array = arrayFilter(array, function(group) {\n if (isArrayLikeObject(group)) {\n length = nativeMax(group.length, length);\n return true;\n }\n });\n return baseTimes(length, function(index) {\n return arrayMap(array, baseProperty(index));\n });\n }\n\n /**\n * This method is like `_.unzip` except that it accepts `iteratee` to specify\n * how regrouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * regrouped values.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip([1, 2], [10, 20], [100, 200]);\n * // => [[1, 10, 100], [2, 20, 200]]\n *\n * _.unzipWith(zipped, _.add);\n * // => [3, 30, 300]\n */\n function unzipWith(array, iteratee) {\n if (!(array && array.length)) {\n return [];\n }\n var result = unzip(array);\n if (iteratee == null) {\n return result;\n }\n return arrayMap(result, function(group) {\n return apply(iteratee, undefined, group);\n });\n }\n\n /**\n * Creates an array excluding all given values using\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * for equality comparisons.\n *\n * **Note:** Unlike `_.pull`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...*} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.xor\n * @example\n *\n * _.without([2, 1, 2, 3], 1, 2);\n * // => [3]\n */\n var without = baseRest(function(array, values) {\n return isArrayLikeObject(array)\n ? baseDifference(array, values)\n : [];\n });\n\n /**\n * Creates an array of unique values that is the\n * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)\n * of the given arrays. The order of result values is determined by the order\n * they occur in the arrays.\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of filtered values.\n * @see _.difference, _.without\n * @example\n *\n * _.xor([2, 1], [2, 3]);\n * // => [1, 3]\n */\n var xor = baseRest(function(arrays) {\n return baseXor(arrayFilter(arrays, isArrayLikeObject));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `iteratee` which is\n * invoked for each element of each `arrays` to generate the criterion by\n * which by which they're compared. The order of result values is determined\n * by the order they occur in the arrays. The iteratee is invoked with one\n * argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);\n * // => [1.2, 3.4]\n *\n * // The `_.property` iteratee shorthand.\n * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 2 }]\n */\n var xorBy = baseRest(function(arrays) {\n var iteratee = last(arrays);\n if (isArrayLikeObject(iteratee)) {\n iteratee = undefined;\n }\n return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));\n });\n\n /**\n * This method is like `_.xor` except that it accepts `comparator` which is\n * invoked to compare elements of `arrays`. The order of result values is\n * determined by the order they occur in the arrays. The comparator is invoked\n * with two arguments: (arrVal, othVal).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @param {Function} [comparator] The comparator invoked per element.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];\n * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];\n *\n * _.xorWith(objects, others, _.isEqual);\n * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]\n */\n var xorWith = baseRest(function(arrays) {\n var comparator = last(arrays);\n comparator = typeof comparator == 'function' ? comparator : undefined;\n return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);\n });\n\n /**\n * Creates an array of grouped elements, the first of which contains the\n * first elements of the given arrays, the second of which contains the\n * second elements of the given arrays, and so on.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zip(['a', 'b'], [1, 2], [true, false]);\n * // => [['a', 1, true], ['b', 2, false]]\n */\n var zip = baseRest(unzip);\n\n /**\n * This method is like `_.fromPairs` except that it accepts two arrays,\n * one of property identifiers and one of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 0.4.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObject(['a', 'b'], [1, 2]);\n * // => { 'a': 1, 'b': 2 }\n */\n function zipObject(props, values) {\n return baseZipObject(props || [], values || [], assignValue);\n }\n\n /**\n * This method is like `_.zipObject` except that it supports property paths.\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Array\n * @param {Array} [props=[]] The property identifiers.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);\n * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }\n */\n function zipObjectDeep(props, values) {\n return baseZipObject(props || [], values || [], baseSet);\n }\n\n /**\n * This method is like `_.zip` except that it accepts `iteratee` to specify\n * how grouped values should be combined. The iteratee is invoked with the\n * elements of each group: (...group).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @param {Function} [iteratee=_.identity] The function to combine\n * grouped values.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {\n * return a + b + c;\n * });\n * // => [111, 222]\n */\n var zipWith = baseRest(function(arrays) {\n var length = arrays.length,\n iteratee = length > 1 ? arrays[length - 1] : undefined;\n\n iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;\n return unzipWith(arrays, iteratee);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` wrapper instance that wraps `value` with explicit method\n * chain sequences enabled. The result of such sequences must be unwrapped\n * with `_#value`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Seq\n * @param {*} value The value to wrap.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'pebbles', 'age': 1 }\n * ];\n *\n * var youngest = _\n * .chain(users)\n * .sortBy('age')\n * .map(function(o) {\n * return o.user + ' is ' + o.age;\n * })\n * .head()\n * .value();\n * // => 'pebbles is 1'\n */\n function chain(value) {\n var result = lodash(value);\n result.__chain__ = true;\n return result;\n }\n\n /**\n * This method invokes `interceptor` and returns `value`. The interceptor\n * is invoked with one argument; (value). The purpose of this method is to\n * \"tap into\" a method chain sequence in order to modify intermediate results.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns `value`.\n * @example\n *\n * _([1, 2, 3])\n * .tap(function(array) {\n * // Mutate input array.\n * array.pop();\n * })\n * .reverse()\n * .value();\n * // => [2, 1]\n */\n function tap(value, interceptor) {\n interceptor(value);\n return value;\n }\n\n /**\n * This method is like `_.tap` except that it returns the result of `interceptor`.\n * The purpose of this method is to \"pass thru\" values replacing intermediate\n * results in a method chain sequence.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Seq\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @returns {*} Returns the result of `interceptor`.\n * @example\n *\n * _(' abc ')\n * .chain()\n * .trim()\n * .thru(function(value) {\n * return [value];\n * })\n * .value();\n * // => ['abc']\n */\n function thru(value, interceptor) {\n return interceptor(value);\n }\n\n /**\n * This method is the wrapper version of `_.at`.\n *\n * @name at\n * @memberOf _\n * @since 1.0.0\n * @category Seq\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _(object).at(['a[0].b.c', 'a[1]']).value();\n * // => [3, 4]\n */\n var wrapperAt = flatRest(function(paths) {\n var length = paths.length,\n start = length ? paths[0] : 0,\n value = this.__wrapped__,\n interceptor = function(object) { return baseAt(object, paths); };\n\n if (length > 1 || this.__actions__.length ||\n !(value instanceof LazyWrapper) || !isIndex(start)) {\n return this.thru(interceptor);\n }\n value = value.slice(start, +start + (length ? 1 : 0));\n value.__actions__.push({\n 'func': thru,\n 'args': [interceptor],\n 'thisArg': undefined\n });\n return new LodashWrapper(value, this.__chain__).thru(function(array) {\n if (length && !array.length) {\n array.push(undefined);\n }\n return array;\n });\n });\n\n /**\n * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.\n *\n * @name chain\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * // A sequence without explicit chaining.\n * _(users).head();\n * // => { 'user': 'barney', 'age': 36 }\n *\n * // A sequence with explicit chaining.\n * _(users)\n * .chain()\n * .head()\n * .pick('user')\n * .value();\n * // => { 'user': 'barney' }\n */\n function wrapperChain() {\n return chain(this);\n }\n\n /**\n * Executes the chain sequence and returns the wrapped result.\n *\n * @name commit\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2];\n * var wrapped = _(array).push(3);\n *\n * console.log(array);\n * // => [1, 2]\n *\n * wrapped = wrapped.commit();\n * console.log(array);\n * // => [1, 2, 3]\n *\n * wrapped.last();\n * // => 3\n *\n * console.log(array);\n * // => [1, 2, 3]\n */\n function wrapperCommit() {\n return new LodashWrapper(this.value(), this.__chain__);\n }\n\n /**\n * Gets the next value on a wrapped object following the\n * [iterator protocol](https://mdn.io/iteration_protocols#iterator).\n *\n * @name next\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the next iterator value.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 1 }\n *\n * wrapped.next();\n * // => { 'done': false, 'value': 2 }\n *\n * wrapped.next();\n * // => { 'done': true, 'value': undefined }\n */\n function wrapperNext() {\n if (this.__values__ === undefined) {\n this.__values__ = toArray(this.value());\n }\n var done = this.__index__ >= this.__values__.length,\n value = done ? undefined : this.__values__[this.__index__++];\n\n return { 'done': done, 'value': value };\n }\n\n /**\n * Enables the wrapper to be iterable.\n *\n * @name Symbol.iterator\n * @memberOf _\n * @since 4.0.0\n * @category Seq\n * @returns {Object} Returns the wrapper object.\n * @example\n *\n * var wrapped = _([1, 2]);\n *\n * wrapped[Symbol.iterator]() === wrapped;\n * // => true\n *\n * Array.from(wrapped);\n * // => [1, 2]\n */\n function wrapperToIterator() {\n return this;\n }\n\n /**\n * Creates a clone of the chain sequence planting `value` as the wrapped value.\n *\n * @name plant\n * @memberOf _\n * @since 3.2.0\n * @category Seq\n * @param {*} value The value to plant.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var wrapped = _([1, 2]).map(square);\n * var other = wrapped.plant([3, 4]);\n *\n * other.value();\n * // => [9, 16]\n *\n * wrapped.value();\n * // => [1, 4]\n */\n function wrapperPlant(value) {\n var result,\n parent = this;\n\n while (parent instanceof baseLodash) {\n var clone = wrapperClone(parent);\n clone.__index__ = 0;\n clone.__values__ = undefined;\n if (result) {\n previous.__wrapped__ = clone;\n } else {\n result = clone;\n }\n var previous = clone;\n parent = parent.__wrapped__;\n }\n previous.__wrapped__ = value;\n return result;\n }\n\n /**\n * This method is the wrapper version of `_.reverse`.\n *\n * **Note:** This method mutates the wrapped array.\n *\n * @name reverse\n * @memberOf _\n * @since 0.1.0\n * @category Seq\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _(array).reverse().value()\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function wrapperReverse() {\n var value = this.__wrapped__;\n if (value instanceof LazyWrapper) {\n var wrapped = value;\n if (this.__actions__.length) {\n wrapped = new LazyWrapper(this);\n }\n wrapped = wrapped.reverse();\n wrapped.__actions__.push({\n 'func': thru,\n 'args': [reverse],\n 'thisArg': undefined\n });\n return new LodashWrapper(wrapped, this.__chain__);\n }\n return this.thru(reverse);\n }\n\n /**\n * Executes the chain sequence to resolve the unwrapped value.\n *\n * @name value\n * @memberOf _\n * @since 0.1.0\n * @alias toJSON, valueOf\n * @category Seq\n * @returns {*} Returns the resolved unwrapped value.\n * @example\n *\n * _([1, 2, 3]).value();\n * // => [1, 2, 3]\n */\n function wrapperValue() {\n return baseWrapperValue(this.__wrapped__, this.__actions__);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the number of times the key was returned by `iteratee`. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.countBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': 1, '6': 2 }\n *\n * // The `_.property` iteratee shorthand.\n * _.countBy(['one', 'two', 'three'], 'length');\n * // => { '3': 2, '5': 1 }\n */\n var countBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n ++result[key];\n } else {\n baseAssignValue(result, key, 1);\n }\n });\n\n /**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * Iteration is stopped once `predicate` returns falsey. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * **Note:** This method returns `true` for\n * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because\n * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of\n * elements of empty collections.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.every(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.every(users, 'active');\n * // => false\n */\n function every(collection, predicate, guard) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * **Note:** Unlike `_.remove`, this method returns a new array.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.reject\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * _.filter(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.filter(users, { 'age': 36, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.filter(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.filter(users, 'active');\n * // => objects for ['barney']\n *\n * // Combining several predicates using `_.overEvery` or `_.overSome`.\n * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));\n * // => objects for ['fred', 'barney']\n */\n function filter(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is invoked with three\n * arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false },\n * { 'user': 'pebbles', 'age': 1, 'active': true }\n * ];\n *\n * _.find(users, function(o) { return o.age < 40; });\n * // => object for 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.find(users, { 'age': 1, 'active': true });\n * // => object for 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.find(users, ['active', false]);\n * // => object for 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.find(users, 'active');\n * // => object for 'barney'\n */\n var find = createFind(findIndex);\n\n /**\n * This method is like `_.find` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param {number} [fromIndex=collection.length-1] The index to search from.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * _.findLast([1, 2, 3, 4], function(n) {\n * return n % 2 == 1;\n * });\n * // => 3\n */\n var findLast = createFind(findLastIndex);\n\n /**\n * Creates a flattened array of values by running each element in `collection`\n * thru `iteratee` and flattening the mapped results. The iteratee is invoked\n * with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [n, n];\n * }\n *\n * _.flatMap([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMap(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), 1);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDeep([1, 2], duplicate);\n * // => [1, 1, 2, 2]\n */\n function flatMapDeep(collection, iteratee) {\n return baseFlatten(map(collection, iteratee), INFINITY);\n }\n\n /**\n * This method is like `_.flatMap` except that it recursively flattens the\n * mapped results up to `depth` times.\n *\n * @static\n * @memberOf _\n * @since 4.7.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {number} [depth=1] The maximum recursion depth.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * function duplicate(n) {\n * return [[[n, n]]];\n * }\n *\n * _.flatMapDepth([1, 2], duplicate, 2);\n * // => [[1, 1], [2, 2]]\n */\n function flatMapDepth(collection, iteratee, depth) {\n depth = depth === undefined ? 1 : toInteger(depth);\n return baseFlatten(map(collection, iteratee), depth);\n }\n\n /**\n * Iterates over elements of `collection` and invokes `iteratee` for each element.\n * The iteratee is invoked with three arguments: (value, index|key, collection).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a \"length\"\n * property are iterated like arrays. To avoid this behavior use `_.forIn`\n * or `_.forOwn` for object iteration.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @alias each\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEachRight\n * @example\n *\n * _.forEach([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `1` then `2`.\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forEach(collection, iteratee) {\n var func = isArray(collection) ? arrayEach : baseEach;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forEach` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @alias eachRight\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array|Object} Returns `collection`.\n * @see _.forEach\n * @example\n *\n * _.forEachRight([1, 2], function(value) {\n * console.log(value);\n * });\n * // => Logs `2` then `1`.\n */\n function forEachRight(collection, iteratee) {\n var func = isArray(collection) ? arrayEachRight : baseEachRight;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The order of grouped values\n * is determined by the order they occur in `collection`. The corresponding\n * value of each key is an array of elements responsible for generating the\n * key. The iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([6.1, 4.2, 6.3], Math.floor);\n * // => { '4': [4.2], '6': [6.1, 6.3] }\n *\n * // The `_.property` iteratee shorthand.\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\n var groupBy = createAggregator(function(result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n result[key].push(value);\n } else {\n baseAssignValue(result, key, [value]);\n }\n });\n\n /**\n * Checks if `value` is in `collection`. If `collection` is a string, it's\n * checked for a substring of `value`, otherwise\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * is used for equality comparisons. If `fromIndex` is negative, it's used as\n * the offset from the end of `collection`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {boolean} Returns `true` if `value` is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'a': 1, 'b': 2 }, 1);\n * // => true\n *\n * _.includes('abcd', 'bc');\n * // => true\n */\n function includes(collection, value, fromIndex, guard) {\n collection = isArrayLike(collection) ? collection : values(collection);\n fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;\n\n var length = collection.length;\n if (fromIndex < 0) {\n fromIndex = nativeMax(length + fromIndex, 0);\n }\n return isString(collection)\n ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)\n : (!!length && baseIndexOf(collection, value, fromIndex) > -1);\n }\n\n /**\n * Invokes the method at `path` of each element in `collection`, returning\n * an array of the results of each invoked method. Any additional arguments\n * are provided to each invoked method. If `path` is a function, it's invoked\n * for, and `this` bound to, each element in `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array|Function|string} path The path of the method to invoke or\n * the function invoked per iteration.\n * @param {...*} [args] The arguments to invoke each method with.\n * @returns {Array} Returns the array of results.\n * @example\n *\n * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');\n * // => [[1, 5, 7], [1, 2, 3]]\n *\n * _.invokeMap([123, 456], String.prototype.split, '');\n * // => [['1', '2', '3'], ['4', '5', '6']]\n */\n var invokeMap = baseRest(function(collection, path, args) {\n var index = -1,\n isFunc = typeof path == 'function',\n result = isArrayLike(collection) ? Array(collection.length) : [];\n\n baseEach(collection, function(value) {\n result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);\n });\n return result;\n });\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` thru `iteratee`. The corresponding value of\n * each key is the last element responsible for generating the key. The\n * iteratee is invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The iteratee to transform keys.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * var array = [\n * { 'dir': 'left', 'code': 97 },\n * { 'dir': 'right', 'code': 100 }\n * ];\n *\n * _.keyBy(array, function(o) {\n * return String.fromCharCode(o.code);\n * });\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n *\n * _.keyBy(array, 'dir');\n * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n */\n var keyBy = createAggregator(function(result, value, key) {\n baseAssignValue(result, key, value);\n });\n\n /**\n * Creates an array of values by running each element in `collection` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,\n * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,\n * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,\n * `template`, `trim`, `trimEnd`, `trimStart`, and `words`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * _.map([4, 8], square);\n * // => [16, 64]\n *\n * _.map({ 'a': 4, 'b': 8 }, square);\n * // => [16, 64] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // The `_.property` iteratee shorthand.\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\n function map(collection, iteratee) {\n var func = isArray(collection) ? arrayMap : baseMap;\n return func(collection, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.sortBy` except that it allows specifying the sort\n * orders of the iteratees to sort by. If `orders` is unspecified, all values\n * are sorted in ascending order. Otherwise, specify an order of \"desc\" for\n * descending or \"asc\" for ascending sort order of corresponding values.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @param {string[]} [orders] The sort orders of `iteratees`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 34 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'barney', 'age': 36 }\n * ];\n *\n * // Sort by `user` in ascending order and by `age` in descending order.\n * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]\n */\n function orderBy(collection, iteratees, orders, guard) {\n if (collection == null) {\n return [];\n }\n if (!isArray(iteratees)) {\n iteratees = iteratees == null ? [] : [iteratees];\n }\n orders = guard ? undefined : orders;\n if (!isArray(orders)) {\n orders = orders == null ? [] : [orders];\n }\n return baseOrderBy(collection, iteratees, orders);\n }\n\n /**\n * Creates an array of elements split into two groups, the first of which\n * contains elements `predicate` returns truthy for, the second of which\n * contains elements `predicate` returns falsey for. The predicate is\n * invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the array of grouped elements.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true },\n * { 'user': 'pebbles', 'age': 1, 'active': false }\n * ];\n *\n * _.partition(users, function(o) { return o.active; });\n * // => objects for [['fred'], ['barney', 'pebbles']]\n *\n * // The `_.matches` iteratee shorthand.\n * _.partition(users, { 'age': 1, 'active': false });\n * // => objects for [['pebbles'], ['barney', 'fred']]\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.partition(users, ['active', false]);\n * // => objects for [['barney', 'pebbles'], ['fred']]\n *\n * // The `_.property` iteratee shorthand.\n * _.partition(users, 'active');\n * // => objects for [['fred'], ['barney', 'pebbles']]\n */\n var partition = createAggregator(function(result, value, key) {\n result[key ? 0 : 1].push(value);\n }, function() { return [[], []]; });\n\n /**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` thru `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not given, the first element of `collection` is used as the initial\n * value. The iteratee is invoked with four arguments:\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as iteratees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,\n * and `sortBy`\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduceRight\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * }, 0);\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * return result;\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)\n */\n function reduce(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduce : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);\n }\n\n /**\n * This method is like `_.reduce` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @returns {*} Returns the accumulated value.\n * @see _.reduce\n * @example\n *\n * var array = [[0, 1], [2, 3], [4, 5]];\n *\n * _.reduceRight(array, function(flattened, other) {\n * return flattened.concat(other);\n * }, []);\n * // => [4, 5, 2, 3, 0, 1]\n */\n function reduceRight(collection, iteratee, accumulator) {\n var func = isArray(collection) ? arrayReduceRight : baseReduce,\n initAccum = arguments.length < 3;\n\n return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);\n }\n\n /**\n * The opposite of `_.filter`; this method returns the elements of `collection`\n * that `predicate` does **not** return truthy for.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n * @see _.filter\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true }\n * ];\n *\n * _.reject(users, function(o) { return !o.active; });\n * // => objects for ['fred']\n *\n * // The `_.matches` iteratee shorthand.\n * _.reject(users, { 'age': 40, 'active': true });\n * // => objects for ['barney']\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.reject(users, ['active', false]);\n * // => objects for ['fred']\n *\n * // The `_.property` iteratee shorthand.\n * _.reject(users, 'active');\n * // => objects for ['barney']\n */\n function reject(collection, predicate) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n return func(collection, negate(getIteratee(predicate, 3)));\n }\n\n /**\n * Gets a random element from `collection`.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @returns {*} Returns the random element.\n * @example\n *\n * _.sample([1, 2, 3, 4]);\n * // => 2\n */\n function sample(collection) {\n var func = isArray(collection) ? arraySample : baseSample;\n return func(collection);\n }\n\n /**\n * Gets `n` random elements at unique keys from `collection` up to the\n * size of `collection`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Collection\n * @param {Array|Object} collection The collection to sample.\n * @param {number} [n=1] The number of elements to sample.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Array} Returns the random elements.\n * @example\n *\n * _.sampleSize([1, 2, 3], 2);\n * // => [3, 1]\n *\n * _.sampleSize([1, 2, 3], 4);\n * // => [2, 3, 1]\n */\n function sampleSize(collection, n, guard) {\n if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n var func = isArray(collection) ? arraySampleSize : baseSampleSize;\n return func(collection, n);\n }\n\n /**\n * Creates an array of shuffled values, using a version of the\n * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n * @example\n *\n * _.shuffle([1, 2, 3, 4]);\n * // => [4, 1, 3, 2]\n */\n function shuffle(collection) {\n var func = isArray(collection) ? arrayShuffle : baseShuffle;\n return func(collection);\n }\n\n /**\n * Gets the size of `collection` by returning its length for array-like\n * values or the number of own enumerable string keyed properties for objects.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @returns {number} Returns the collection size.\n * @example\n *\n * _.size([1, 2, 3]);\n * // => 3\n *\n * _.size({ 'a': 1, 'b': 2 });\n * // => 2\n *\n * _.size('pebbles');\n * // => 7\n */\n function size(collection) {\n if (collection == null) {\n return 0;\n }\n if (isArrayLike(collection)) {\n return isString(collection) ? stringSize(collection) : collection.length;\n }\n var tag = getTag(collection);\n if (tag == mapTag || tag == setTag) {\n return collection.size;\n }\n return baseKeys(collection).length;\n }\n\n /**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * Iteration is stopped once `predicate` returns truthy. The predicate is\n * invoked with three arguments: (value, index|key, collection).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // The `_.matches` iteratee shorthand.\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.some(users, ['active', false]);\n * // => true\n *\n * // The `_.property` iteratee shorthand.\n * _.some(users, 'active');\n * // => true\n */\n function some(collection, predicate, guard) {\n var func = isArray(collection) ? arraySome : baseSome;\n if (guard && isIterateeCall(collection, predicate, guard)) {\n predicate = undefined;\n }\n return func(collection, getIteratee(predicate, 3));\n }\n\n /**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection thru each iteratee. This method\n * performs a stable sort, that is, it preserves the original sort order of\n * equal elements. The iteratees are invoked with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Collection\n * @param {Array|Object} collection The collection to iterate over.\n * @param {...(Function|Function[])} [iteratees=[_.identity]]\n * The iteratees to sort by.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'fred', 'age': 48 },\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 30 },\n * { 'user': 'barney', 'age': 34 }\n * ];\n *\n * _.sortBy(users, [function(o) { return o.user; }]);\n * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]\n *\n * _.sortBy(users, ['user', 'age']);\n * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]\n */\n var sortBy = baseRest(function(collection, iteratees) {\n if (collection == null) {\n return [];\n }\n var length = iteratees.length;\n if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {\n iteratees = [];\n } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {\n iteratees = [iteratees[0]];\n }\n return baseOrderBy(collection, baseFlatten(iteratees, 1), []);\n });\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Gets the timestamp of the number of milliseconds that have elapsed since\n * the Unix epoch (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Date\n * @returns {number} Returns the timestamp.\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => Logs the number of milliseconds it took for the deferred invocation.\n */\n var now = ctxNow || function() {\n return root.Date.now();\n };\n\n /*------------------------------------------------------------------------*/\n\n /**\n * The opposite of `_.before`; this method creates a function that invokes\n * `func` once it's called `n` or more times.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {number} n The number of calls before `func` is invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var saves = ['profile', 'settings'];\n *\n * var done = _.after(saves.length, function() {\n * console.log('done saving!');\n * });\n *\n * _.forEach(saves, function(type) {\n * asyncSave({ 'type': type, 'complete': done });\n * });\n * // => Logs 'done saving!' after the two async saves have completed.\n */\n function after(n, func) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n < 1) {\n return func.apply(this, arguments);\n }\n };\n }\n\n /**\n * Creates a function that invokes `func`, with up to `n` arguments,\n * ignoring any additional arguments.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @param {number} [n=func.length] The arity cap.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n * // => [6, 8, 10]\n */\n function ary(func, n, guard) {\n n = guard ? undefined : n;\n n = (func && n == null) ? func.length : n;\n return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);\n }\n\n /**\n * Creates a function that invokes `func`, with the `this` binding and arguments\n * of the created function, while it's called less than `n` times. Subsequent\n * calls to the created function return the result of the last `func` invocation.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {number} n The number of calls at which `func` is no longer invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * jQuery(element).on('click', _.before(5, addContactToList));\n * // => Allows adding up to 4 contacts to the list.\n */\n function before(n, func) {\n var result;\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n n = toInteger(n);\n return function() {\n if (--n > 0) {\n result = func.apply(this, arguments);\n }\n if (n <= 1) {\n func = undefined;\n }\n return result;\n };\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of `thisArg`\n * and `partials` prepended to the arguments it receives.\n *\n * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for partially applied arguments.\n *\n * **Note:** Unlike native `Function#bind`, this method doesn't set the \"length\"\n * property of bound functions.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to bind.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * function greet(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n *\n * var object = { 'user': 'fred' };\n *\n * var bound = _.bind(greet, object, 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bind(greet, object, _, '!');\n * bound('hi');\n * // => 'hi fred!'\n */\n var bind = baseRest(function(func, thisArg, partials) {\n var bitmask = WRAP_BIND_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bind));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(func, bitmask, thisArg, partials, holders);\n });\n\n /**\n * Creates a function that invokes the method at `object[key]` with `partials`\n * prepended to the arguments it receives.\n *\n * This method differs from `_.bind` by allowing bound functions to reference\n * methods that may be redefined or don't yet exist. See\n * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)\n * for more details.\n *\n * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Function\n * @param {Object} object The object to invoke the method on.\n * @param {string} key The key of the method.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * var object = {\n * 'user': 'fred',\n * 'greet': function(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n * };\n *\n * var bound = _.bindKey(object, 'greet', 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * object.greet = function(greeting, punctuation) {\n * return greeting + 'ya ' + this.user + punctuation;\n * };\n *\n * bound('!');\n * // => 'hiya fred!'\n *\n * // Bound with placeholders.\n * var bound = _.bindKey(object, 'greet', _, '!');\n * bound('hi');\n * // => 'hiya fred!'\n */\n var bindKey = baseRest(function(object, key, partials) {\n var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;\n if (partials.length) {\n var holders = replaceHolders(partials, getHolder(bindKey));\n bitmask |= WRAP_PARTIAL_FLAG;\n }\n return createWrap(key, bitmask, object, partials, holders);\n });\n\n /**\n * Creates a function that accepts arguments of `func` and either invokes\n * `func` returning its result, if at least `arity` number of arguments have\n * been provided, or returns a function that accepts the remaining `func`\n * arguments, and so on. The arity of `func` may be specified if `func.length`\n * is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\n function curry(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curry.placeholder;\n return result;\n }\n\n /**\n * This method is like `_.curry` except that arguments are applied to `func`\n * in the manner of `_.partialRight` instead of `_.partial`.\n *\n * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for provided arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of curried functions.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curryRight(abc);\n *\n * curried(3)(2)(1);\n * // => [1, 2, 3]\n *\n * curried(2, 3)(1);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // Curried with placeholders.\n * curried(3)(1, _)(2);\n * // => [1, 2, 3]\n */\n function curryRight(func, arity, guard) {\n arity = guard ? undefined : arity;\n var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);\n result.placeholder = curryRight.placeholder;\n return result;\n }\n\n /**\n * Creates a debounced function that delays invoking `func` until after `wait`\n * milliseconds have elapsed since the last time the debounced function was\n * invoked. The debounced function comes with a `cancel` method to cancel\n * delayed `func` invocations and a `flush` method to immediately invoke them.\n * Provide `options` to indicate whether `func` should be invoked on the\n * leading and/or trailing edge of the `wait` timeout. The `func` is invoked\n * with the last arguments provided to the debounced function. Subsequent\n * calls to the debounced function return the result of the last `func`\n * invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the debounced function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=false]\n * Specify invoking on the leading edge of the timeout.\n * @param {number} [options.maxWait]\n * The maximum time `func` is allowed to be delayed before it's invoked.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // Avoid costly calculations while the window size is in flux.\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // Invoke `sendMail` when clicked, debouncing subsequent calls.\n * jQuery(element).on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // Ensure `batchLog` is invoked once after 1 second of debounced calls.\n * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', debounced);\n *\n * // Cancel the trailing debounced invocation.\n * jQuery(window).on('popstate', debounced.cancel);\n */\n function debounce(func, wait, options) {\n var lastArgs,\n lastThis,\n maxWait,\n result,\n timerId,\n lastCallTime,\n lastInvokeTime = 0,\n leading = false,\n maxing = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = toNumber(wait) || 0;\n if (isObject(options)) {\n leading = !!options.leading;\n maxing = 'maxWait' in options;\n maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n\n function invokeFunc(time) {\n var args = lastArgs,\n thisArg = lastThis;\n\n lastArgs = lastThis = undefined;\n lastInvokeTime = time;\n result = func.apply(thisArg, args);\n return result;\n }\n\n function leadingEdge(time) {\n // Reset any `maxWait` timer.\n lastInvokeTime = time;\n // Start the timer for the trailing edge.\n timerId = setTimeout(timerExpired, wait);\n // Invoke the leading edge.\n return leading ? invokeFunc(time) : result;\n }\n\n function remainingWait(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime,\n timeWaiting = wait - timeSinceLastCall;\n\n return maxing\n ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)\n : timeWaiting;\n }\n\n function shouldInvoke(time) {\n var timeSinceLastCall = time - lastCallTime,\n timeSinceLastInvoke = time - lastInvokeTime;\n\n // Either this is the first call, activity has stopped and we're at the\n // trailing edge, the system time has gone backwards and we're treating\n // it as the trailing edge, or we've hit the `maxWait` limit.\n return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||\n (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));\n }\n\n function timerExpired() {\n var time = now();\n if (shouldInvoke(time)) {\n return trailingEdge(time);\n }\n // Restart the timer.\n timerId = setTimeout(timerExpired, remainingWait(time));\n }\n\n function trailingEdge(time) {\n timerId = undefined;\n\n // Only invoke if we have `lastArgs` which means `func` has been\n // debounced at least once.\n if (trailing && lastArgs) {\n return invokeFunc(time);\n }\n lastArgs = lastThis = undefined;\n return result;\n }\n\n function cancel() {\n if (timerId !== undefined) {\n clearTimeout(timerId);\n }\n lastInvokeTime = 0;\n lastArgs = lastCallTime = lastThis = timerId = undefined;\n }\n\n function flush() {\n return timerId === undefined ? result : trailingEdge(now());\n }\n\n function debounced() {\n var time = now(),\n isInvoking = shouldInvoke(time);\n\n lastArgs = arguments;\n lastThis = this;\n lastCallTime = time;\n\n if (isInvoking) {\n if (timerId === undefined) {\n return leadingEdge(lastCallTime);\n }\n if (maxing) {\n // Handle invocations in a tight loop.\n clearTimeout(timerId);\n timerId = setTimeout(timerExpired, wait);\n return invokeFunc(lastCallTime);\n }\n }\n if (timerId === undefined) {\n timerId = setTimeout(timerExpired, wait);\n }\n return result;\n }\n debounced.cancel = cancel;\n debounced.flush = flush;\n return debounced;\n }\n\n /**\n * Defers invoking the `func` until the current call stack has cleared. Any\n * additional arguments are provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to defer.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function(text) {\n * console.log(text);\n * }, 'deferred');\n * // => Logs 'deferred' after one millisecond.\n */\n var defer = baseRest(function(func, args) {\n return baseDelay(func, 1, args);\n });\n\n /**\n * Invokes `func` after `wait` milliseconds. Any additional arguments are\n * provided to `func` when it's invoked.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {...*} [args] The arguments to invoke `func` with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.delay(function(text) {\n * console.log(text);\n * }, 1000, 'later');\n * // => Logs 'later' after one second.\n */\n var delay = baseRest(function(func, wait, args) {\n return baseDelay(func, toNumber(wait) || 0, args);\n });\n\n /**\n * Creates a function that invokes `func` with arguments reversed.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to flip arguments for.\n * @returns {Function} Returns the new flipped function.\n * @example\n *\n * var flipped = _.flip(function() {\n * return _.toArray(arguments);\n * });\n *\n * flipped('a', 'b', 'c', 'd');\n * // => ['d', 'c', 'b', 'a']\n */\n function flip(func) {\n return createWrap(func, WRAP_FLIP_FLAG);\n }\n\n /**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided, it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is used as the map cache key. The `func`\n * is invoked with the `this` binding of the memoized function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the\n * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)\n * method interface of `clear`, `delete`, `get`, `has`, and `set`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoized function.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n * var other = { 'c': 3, 'd': 4 };\n *\n * var values = _.memoize(_.values);\n * values(object);\n * // => [1, 2]\n *\n * values(other);\n * // => [3, 4]\n *\n * object.a = 2;\n * values(object);\n * // => [1, 2]\n *\n * // Modify the result cache.\n * values.cache.set(object, ['a', 'b']);\n * values(object);\n * // => ['a', 'b']\n *\n * // Replace `_.memoize.Cache`.\n * _.memoize.Cache = WeakMap;\n */\n function memoize(func, resolver) {\n if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function() {\n var args = arguments,\n key = resolver ? resolver.apply(this, args) : args[0],\n cache = memoized.cache;\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, args);\n memoized.cache = cache.set(key, result) || cache;\n return result;\n };\n memoized.cache = new (memoize.Cache || MapCache);\n return memoized;\n }\n\n // Expose `MapCache`.\n memoize.Cache = MapCache;\n\n /**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new negated function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\n function negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function() {\n var args = arguments;\n switch (args.length) {\n case 0: return !predicate.call(this);\n case 1: return !predicate.call(this, args[0]);\n case 2: return !predicate.call(this, args[0], args[1]);\n case 3: return !predicate.call(this, args[0], args[1], args[2]);\n }\n return !predicate.apply(this, args);\n };\n }\n\n /**\n * Creates a function that is restricted to invoking `func` once. Repeat calls\n * to the function return the value of the first invocation. The `func` is\n * invoked with the `this` binding and arguments of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var initialize = _.once(createApplication);\n * initialize();\n * initialize();\n * // => `createApplication` is invoked once\n */\n function once(func) {\n return before(2, func);\n }\n\n /**\n * Creates a function that invokes `func` with its arguments transformed.\n *\n * @static\n * @since 4.0.0\n * @memberOf _\n * @category Function\n * @param {Function} func The function to wrap.\n * @param {...(Function|Function[])} [transforms=[_.identity]]\n * The argument transforms.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function doubled(n) {\n * return n * 2;\n * }\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var func = _.overArgs(function(x, y) {\n * return [x, y];\n * }, [square, doubled]);\n *\n * func(9, 3);\n * // => [81, 6]\n *\n * func(10, 5);\n * // => [100, 10]\n */\n var overArgs = castRest(function(func, transforms) {\n transforms = (transforms.length == 1 && isArray(transforms[0]))\n ? arrayMap(transforms[0], baseUnary(getIteratee()))\n : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));\n\n var funcsLength = transforms.length;\n return baseRest(function(args) {\n var index = -1,\n length = nativeMin(args.length, funcsLength);\n\n while (++index < length) {\n args[index] = transforms[index].call(this, args[index]);\n }\n return apply(func, this, args);\n });\n });\n\n /**\n * Creates a function that invokes `func` with `partials` prepended to the\n * arguments it receives. This method is like `_.bind` except it does **not**\n * alter the `this` binding.\n *\n * The `_.partial.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 0.2.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var sayHelloTo = _.partial(greet, 'hello');\n * sayHelloTo('fred');\n * // => 'hello fred'\n *\n * // Partially applied with placeholders.\n * var greetFred = _.partial(greet, _, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n */\n var partial = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partial));\n return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);\n });\n\n /**\n * This method is like `_.partial` except that partially applied arguments\n * are appended to the arguments it receives.\n *\n * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method doesn't set the \"length\" property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [partials] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * function greet(greeting, name) {\n * return greeting + ' ' + name;\n * }\n *\n * var greetFred = _.partialRight(greet, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n *\n * // Partially applied with placeholders.\n * var sayHelloTo = _.partialRight(greet, 'hello', _);\n * sayHelloTo('fred');\n * // => 'hello fred'\n */\n var partialRight = baseRest(function(func, partials) {\n var holders = replaceHolders(partials, getHolder(partialRight));\n return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);\n });\n\n /**\n * Creates a function that invokes `func` with arguments arranged according\n * to the specified `indexes` where the argument value at the first index is\n * provided as the first argument, the argument value at the second index is\n * provided as the second argument, and so on.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Function\n * @param {Function} func The function to rearrange arguments for.\n * @param {...(number|number[])} indexes The arranged argument indexes.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var rearged = _.rearg(function(a, b, c) {\n * return [a, b, c];\n * }, [2, 0, 1]);\n *\n * rearged('b', 'c', 'a')\n * // => ['a', 'b', 'c']\n */\n var rearg = flatRest(function(func, indexes) {\n return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);\n });\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * created function and arguments from `start` and beyond provided as\n * an array.\n *\n * **Note:** This method is based on the\n * [rest parameter](https://mdn.io/rest_parameters).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to apply a rest parameter to.\n * @param {number} [start=func.length-1] The start position of the rest parameter.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.rest(function(what, names) {\n * return what + ' ' + _.initial(names).join(', ') +\n * (_.size(names) > 1 ? ', & ' : '') + _.last(names);\n * });\n *\n * say('hello', 'fred', 'barney', 'pebbles');\n * // => 'hello fred, barney, & pebbles'\n */\n function rest(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start === undefined ? start : toInteger(start);\n return baseRest(func, start);\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * create function and an array of arguments much like\n * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).\n *\n * **Note:** This method is based on the\n * [spread operator](https://mdn.io/spread_operator).\n *\n * @static\n * @memberOf _\n * @since 3.2.0\n * @category Function\n * @param {Function} func The function to spread arguments over.\n * @param {number} [start=0] The start position of the spread.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var say = _.spread(function(who, what) {\n * return who + ' says ' + what;\n * });\n *\n * say(['fred', 'hello']);\n * // => 'fred says hello'\n *\n * var numbers = Promise.all([\n * Promise.resolve(40),\n * Promise.resolve(36)\n * ]);\n *\n * numbers.then(_.spread(function(x, y) {\n * return x + y;\n * }));\n * // => a Promise of 76\n */\n function spread(func, start) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n start = start == null ? 0 : nativeMax(toInteger(start), 0);\n return baseRest(function(args) {\n var array = args[start],\n otherArgs = castSlice(args, 0, start);\n\n if (array) {\n arrayPush(otherArgs, array);\n }\n return apply(func, this, otherArgs);\n });\n }\n\n /**\n * Creates a throttled function that only invokes `func` at most once per\n * every `wait` milliseconds. The throttled function comes with a `cancel`\n * method to cancel delayed `func` invocations and a `flush` method to\n * immediately invoke them. Provide `options` to indicate whether `func`\n * should be invoked on the leading and/or trailing edge of the `wait`\n * timeout. The `func` is invoked with the last arguments provided to the\n * throttled function. Subsequent calls to the throttled function return the\n * result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is\n * invoked on the trailing edge of the timeout only if the throttled function\n * is invoked more than once during the `wait` timeout.\n *\n * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred\n * until to the next tick, similar to `setTimeout` with a timeout of `0`.\n *\n * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options={}] The options object.\n * @param {boolean} [options.leading=true]\n * Specify invoking on the leading edge of the timeout.\n * @param {boolean} [options.trailing=true]\n * Specify invoking on the trailing edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // Avoid excessively updating the position while scrolling.\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.\n * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });\n * jQuery(element).on('click', throttled);\n *\n * // Cancel the trailing throttled invocation.\n * jQuery(window).on('popstate', throttled.cancel);\n */\n function throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n return debounce(func, wait, {\n 'leading': leading,\n 'maxWait': wait,\n 'trailing': trailing\n });\n }\n\n /**\n * Creates a function that accepts up to one argument, ignoring any\n * additional arguments.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @returns {Function} Returns the new capped function.\n * @example\n *\n * _.map(['6', '8', '10'], _.unary(parseInt));\n * // => [6, 8, 10]\n */\n function unary(func) {\n return ary(func, 1);\n }\n\n /**\n * Creates a function that provides `value` to `wrapper` as its first\n * argument. Any additional arguments provided to the function are appended\n * to those provided to the `wrapper`. The wrapper is invoked with the `this`\n * binding of the created function.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Function\n * @param {*} value The value to wrap.\n * @param {Function} [wrapper=identity] The wrapper function.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var p = _.wrap(_.escape, function(func, text) {\n * return '

' + func(text) + '

';\n * });\n *\n * p('fred, barney, & pebbles');\n * // => '

fred, barney, & pebbles

'\n */\n function wrap(value, wrapper) {\n return partial(castFunction(wrapper), value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Casts `value` as an array if it's not one.\n *\n * @static\n * @memberOf _\n * @since 4.4.0\n * @category Lang\n * @param {*} value The value to inspect.\n * @returns {Array} Returns the cast array.\n * @example\n *\n * _.castArray(1);\n * // => [1]\n *\n * _.castArray({ 'a': 1 });\n * // => [{ 'a': 1 }]\n *\n * _.castArray('abc');\n * // => ['abc']\n *\n * _.castArray(null);\n * // => [null]\n *\n * _.castArray(undefined);\n * // => [undefined]\n *\n * _.castArray();\n * // => []\n *\n * var array = [1, 2, 3];\n * console.log(_.castArray(array) === array);\n * // => true\n */\n function castArray() {\n if (!arguments.length) {\n return [];\n }\n var value = arguments[0];\n return isArray(value) ? value : [value];\n }\n\n /**\n * Creates a shallow clone of `value`.\n *\n * **Note:** This method is loosely based on the\n * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)\n * and supports cloning arrays, array buffers, booleans, date objects, maps,\n * numbers, `Object` objects, regexes, sets, strings, symbols, and typed\n * arrays. The own enumerable properties of `arguments` objects are cloned\n * as plain objects. An empty object is returned for uncloneable values such\n * as error objects, functions, DOM nodes, and WeakMaps.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to clone.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeep\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var shallow = _.clone(objects);\n * console.log(shallow[0] === objects[0]);\n * // => true\n */\n function clone(value) {\n return baseClone(value, CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.clone` except that it accepts `customizer` which\n * is invoked to produce the cloned value. If `customizer` returns `undefined`,\n * cloning is handled by the method instead. The `customizer` is invoked with\n * up to four arguments; (value [, index|key, object, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the cloned value.\n * @see _.cloneDeepWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(false);\n * }\n * }\n *\n * var el = _.cloneWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 0\n */\n function cloneWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * This method is like `_.clone` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @returns {*} Returns the deep cloned value.\n * @see _.clone\n * @example\n *\n * var objects = [{ 'a': 1 }, { 'b': 2 }];\n *\n * var deep = _.cloneDeep(objects);\n * console.log(deep[0] === objects[0]);\n * // => false\n */\n function cloneDeep(value) {\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);\n }\n\n /**\n * This method is like `_.cloneWith` except that it recursively clones `value`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to recursively clone.\n * @param {Function} [customizer] The function to customize cloning.\n * @returns {*} Returns the deep cloned value.\n * @see _.cloneWith\n * @example\n *\n * function customizer(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(true);\n * }\n * }\n *\n * var el = _.cloneDeepWith(document.body, customizer);\n *\n * console.log(el === document.body);\n * // => false\n * console.log(el.nodeName);\n * // => 'BODY'\n * console.log(el.childNodes.length);\n * // => 20\n */\n function cloneDeepWith(value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);\n }\n\n /**\n * Checks if `object` conforms to `source` by invoking the predicate\n * properties of `source` with the corresponding property values of `object`.\n *\n * **Note:** This method is equivalent to `_.conforms` when `source` is\n * partially applied.\n *\n * @static\n * @memberOf _\n * @since 4.14.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property predicates to conform to.\n * @returns {boolean} Returns `true` if `object` conforms, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 1; } });\n * // => true\n *\n * _.conformsTo(object, { 'b': function(n) { return n > 2; } });\n * // => false\n */\n function conformsTo(object, source) {\n return source == null || baseConformsTo(object, source, keys(source));\n }\n\n /**\n * Performs a\n * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)\n * comparison between two values to determine if they are equivalent.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.eq(object, object);\n * // => true\n *\n * _.eq(object, other);\n * // => false\n *\n * _.eq('a', 'a');\n * // => true\n *\n * _.eq('a', Object('a'));\n * // => false\n *\n * _.eq(NaN, NaN);\n * // => true\n */\n function eq(value, other) {\n return value === other || (value !== value && other !== other);\n }\n\n /**\n * Checks if `value` is greater than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than `other`,\n * else `false`.\n * @see _.lt\n * @example\n *\n * _.gt(3, 1);\n * // => true\n *\n * _.gt(3, 3);\n * // => false\n *\n * _.gt(1, 3);\n * // => false\n */\n var gt = createRelationalOperation(baseGt);\n\n /**\n * Checks if `value` is greater than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is greater than or equal to\n * `other`, else `false`.\n * @see _.lte\n * @example\n *\n * _.gte(3, 1);\n * // => true\n *\n * _.gte(3, 3);\n * // => true\n *\n * _.gte(1, 3);\n * // => false\n */\n var gte = createRelationalOperation(function(value, other) {\n return value >= other;\n });\n\n /**\n * Checks if `value` is likely an `arguments` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an `arguments` object,\n * else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\n var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {\n return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&\n !propertyIsEnumerable.call(value, 'callee');\n };\n\n /**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(document.body.children);\n * // => false\n *\n * _.isArray('abc');\n * // => false\n *\n * _.isArray(_.noop);\n * // => false\n */\n var isArray = Array.isArray;\n\n /**\n * Checks if `value` is classified as an `ArrayBuffer` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.\n * @example\n *\n * _.isArrayBuffer(new ArrayBuffer(2));\n * // => true\n *\n * _.isArrayBuffer(new Array(2));\n * // => false\n */\n var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;\n\n /**\n * Checks if `value` is array-like. A value is considered array-like if it's\n * not a function and has a `value.length` that's an integer greater than or\n * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is array-like, else `false`.\n * @example\n *\n * _.isArrayLike([1, 2, 3]);\n * // => true\n *\n * _.isArrayLike(document.body.children);\n * // => true\n *\n * _.isArrayLike('abc');\n * // => true\n *\n * _.isArrayLike(_.noop);\n * // => false\n */\n function isArrayLike(value) {\n return value != null && isLength(value.length) && !isFunction(value);\n }\n\n /**\n * This method is like `_.isArrayLike` except that it also checks if `value`\n * is an object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an array-like object,\n * else `false`.\n * @example\n *\n * _.isArrayLikeObject([1, 2, 3]);\n * // => true\n *\n * _.isArrayLikeObject(document.body.children);\n * // => true\n *\n * _.isArrayLikeObject('abc');\n * // => false\n *\n * _.isArrayLikeObject(_.noop);\n * // => false\n */\n function isArrayLikeObject(value) {\n return isObjectLike(value) && isArrayLike(value);\n }\n\n /**\n * Checks if `value` is classified as a boolean primitive or object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\n function isBoolean(value) {\n return value === true || value === false ||\n (isObjectLike(value) && baseGetTag(value) == boolTag);\n }\n\n /**\n * Checks if `value` is a buffer.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.\n * @example\n *\n * _.isBuffer(new Buffer(2));\n * // => true\n *\n * _.isBuffer(new Uint8Array(2));\n * // => false\n */\n var isBuffer = nativeIsBuffer || stubFalse;\n\n /**\n * Checks if `value` is classified as a `Date` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a date object, else `false`.\n * @example\n *\n * _.isDate(new Date);\n * // => true\n *\n * _.isDate('Mon April 23 2012');\n * // => false\n */\n var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;\n\n /**\n * Checks if `value` is likely a DOM element.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.\n * @example\n *\n * _.isElement(document.body);\n * // => true\n *\n * _.isElement('');\n * // => false\n */\n function isElement(value) {\n return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);\n }\n\n /**\n * Checks if `value` is an empty object, collection, map, or set.\n *\n * Objects are considered empty if they have no own enumerable string keyed\n * properties.\n *\n * Array-like values such as `arguments` objects, arrays, buffers, strings, or\n * jQuery-like collections are considered empty if they have a `length` of `0`.\n * Similarly, maps and sets are considered empty if they have a `size` of `0`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\n function isEmpty(value) {\n if (value == null) {\n return true;\n }\n if (isArrayLike(value) &&\n (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||\n isBuffer(value) || isTypedArray(value) || isArguments(value))) {\n return !value.length;\n }\n var tag = getTag(value);\n if (tag == mapTag || tag == setTag) {\n return !value.size;\n }\n if (isPrototype(value)) {\n return !baseKeys(value).length;\n }\n for (var key in value) {\n if (hasOwnProperty.call(value, key)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Performs a deep comparison between two values to determine if they are\n * equivalent.\n *\n * **Note:** This method supports comparing arrays, array buffers, booleans,\n * date objects, error objects, maps, numbers, `Object` objects, regexes,\n * sets, strings, symbols, and typed arrays. `Object` objects are compared\n * by their own, not inherited, enumerable properties. Functions and DOM\n * nodes are compared by strict equality, i.e. `===`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'a': 1 };\n * var other = { 'a': 1 };\n *\n * _.isEqual(object, other);\n * // => true\n *\n * object === other;\n * // => false\n */\n function isEqual(value, other) {\n return baseIsEqual(value, other);\n }\n\n /**\n * This method is like `_.isEqual` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with up to\n * six arguments: (objValue, othValue [, index|key, object, other, stack]).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, othValue) {\n * if (isGreeting(objValue) && isGreeting(othValue)) {\n * return true;\n * }\n * }\n *\n * var array = ['hello', 'goodbye'];\n * var other = ['hi', 'goodbye'];\n *\n * _.isEqualWith(array, other, customizer);\n * // => true\n */\n function isEqualWith(value, other, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n var result = customizer ? customizer(value, other) : undefined;\n return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;\n }\n\n /**\n * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n * `SyntaxError`, `TypeError`, or `URIError` object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an error object, else `false`.\n * @example\n *\n * _.isError(new Error);\n * // => true\n *\n * _.isError(Error);\n * // => false\n */\n function isError(value) {\n if (!isObjectLike(value)) {\n return false;\n }\n var tag = baseGetTag(value);\n return tag == errorTag || tag == domExcTag ||\n (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));\n }\n\n /**\n * Checks if `value` is a finite primitive number.\n *\n * **Note:** This method is based on\n * [`Number.isFinite`](https://mdn.io/Number/isFinite).\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.\n * @example\n *\n * _.isFinite(3);\n * // => true\n *\n * _.isFinite(Number.MIN_VALUE);\n * // => true\n *\n * _.isFinite(Infinity);\n * // => false\n *\n * _.isFinite('3');\n * // => false\n */\n function isFinite(value) {\n return typeof value == 'number' && nativeIsFinite(value);\n }\n\n /**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a function, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\n function isFunction(value) {\n if (!isObject(value)) {\n return false;\n }\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in Safari 9 which returns 'object' for typed arrays and other constructors.\n var tag = baseGetTag(value);\n return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;\n }\n\n /**\n * Checks if `value` is an integer.\n *\n * **Note:** This method is based on\n * [`Number.isInteger`](https://mdn.io/Number/isInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an integer, else `false`.\n * @example\n *\n * _.isInteger(3);\n * // => true\n *\n * _.isInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isInteger(Infinity);\n * // => false\n *\n * _.isInteger('3');\n * // => false\n */\n function isInteger(value) {\n return typeof value == 'number' && value == toInteger(value);\n }\n\n /**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This method is loosely based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n * @example\n *\n * _.isLength(3);\n * // => true\n *\n * _.isLength(Number.MIN_VALUE);\n * // => false\n *\n * _.isLength(Infinity);\n * // => false\n *\n * _.isLength('3');\n * // => false\n */\n function isLength(value) {\n return typeof value == 'number' &&\n value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is the\n * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)\n * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(_.noop);\n * // => true\n *\n * _.isObject(null);\n * // => false\n */\n function isObject(value) {\n var type = typeof value;\n return value != null && (type == 'object' || type == 'function');\n }\n\n /**\n * Checks if `value` is object-like. A value is object-like if it's not `null`\n * and has a `typeof` result of \"object\".\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n * @example\n *\n * _.isObjectLike({});\n * // => true\n *\n * _.isObjectLike([1, 2, 3]);\n * // => true\n *\n * _.isObjectLike(_.noop);\n * // => false\n *\n * _.isObjectLike(null);\n * // => false\n */\n function isObjectLike(value) {\n return value != null && typeof value == 'object';\n }\n\n /**\n * Checks if `value` is classified as a `Map` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a map, else `false`.\n * @example\n *\n * _.isMap(new Map);\n * // => true\n *\n * _.isMap(new WeakMap);\n * // => false\n */\n var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;\n\n /**\n * Performs a partial deep comparison between `object` and `source` to\n * determine if `object` contains equivalent property values.\n *\n * **Note:** This method is equivalent to `_.matches` when `source` is\n * partially applied.\n *\n * Partial comparisons will match empty array and empty object `source`\n * values against any array or object value, respectively. See `_.isEqual`\n * for a list of supported value comparisons.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2 };\n *\n * _.isMatch(object, { 'b': 2 });\n * // => true\n *\n * _.isMatch(object, { 'b': 1 });\n * // => false\n */\n function isMatch(object, source) {\n return object === source || baseIsMatch(object, source, getMatchData(source));\n }\n\n /**\n * This method is like `_.isMatch` except that it accepts `customizer` which\n * is invoked to compare values. If `customizer` returns `undefined`, comparisons\n * are handled by the method instead. The `customizer` is invoked with five\n * arguments: (objValue, srcValue, index|key, object, source).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Function} [customizer] The function to customize comparisons.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * function isGreeting(value) {\n * return /^h(?:i|ello)$/.test(value);\n * }\n *\n * function customizer(objValue, srcValue) {\n * if (isGreeting(objValue) && isGreeting(srcValue)) {\n * return true;\n * }\n * }\n *\n * var object = { 'greeting': 'hello' };\n * var source = { 'greeting': 'hi' };\n *\n * _.isMatchWith(object, source, customizer);\n * // => true\n */\n function isMatchWith(object, source, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return baseIsMatch(object, source, getMatchData(source), customizer);\n }\n\n /**\n * Checks if `value` is `NaN`.\n *\n * **Note:** This method is based on\n * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as\n * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for\n * `undefined` and other non-number values.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n * @example\n *\n * _.isNaN(NaN);\n * // => true\n *\n * _.isNaN(new Number(NaN));\n * // => true\n *\n * isNaN(undefined);\n * // => true\n *\n * _.isNaN(undefined);\n * // => false\n */\n function isNaN(value) {\n // An `NaN` primitive is the only value that is not equal to itself.\n // Perform the `toStringTag` check first to avoid errors with some\n // ActiveX objects in IE.\n return isNumber(value) && value != +value;\n }\n\n /**\n * Checks if `value` is a pristine native function.\n *\n * **Note:** This method can't reliably detect native functions in the presence\n * of the core-js package because core-js circumvents this kind of detection.\n * Despite multiple requests, the core-js maintainer has made it clear: any\n * attempt to fix the detection will be obstructed. As a result, we're left\n * with little choice but to throw an error. Unfortunately, this also affects\n * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),\n * which rely on core-js.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function,\n * else `false`.\n * @example\n *\n * _.isNative(Array.prototype.push);\n * // => true\n *\n * _.isNative(_);\n * // => false\n */\n function isNative(value) {\n if (isMaskable(value)) {\n throw new Error(CORE_ERROR_TEXT);\n }\n return baseIsNative(value);\n }\n\n /**\n * Checks if `value` is `null`.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\n function isNull(value) {\n return value === null;\n }\n\n /**\n * Checks if `value` is `null` or `undefined`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is nullish, else `false`.\n * @example\n *\n * _.isNil(null);\n * // => true\n *\n * _.isNil(void 0);\n * // => true\n *\n * _.isNil(NaN);\n * // => false\n */\n function isNil(value) {\n return value == null;\n }\n\n /**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are\n * classified as numbers, use the `_.isFinite` method.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a number, else `false`.\n * @example\n *\n * _.isNumber(3);\n * // => true\n *\n * _.isNumber(Number.MIN_VALUE);\n * // => true\n *\n * _.isNumber(Infinity);\n * // => true\n *\n * _.isNumber('3');\n * // => false\n */\n function isNumber(value) {\n return typeof value == 'number' ||\n (isObjectLike(value) && baseGetTag(value) == numberTag);\n }\n\n /**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * @static\n * @memberOf _\n * @since 0.8.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\n function isPlainObject(value) {\n if (!isObjectLike(value) || baseGetTag(value) != objectTag) {\n return false;\n }\n var proto = getPrototype(value);\n if (proto === null) {\n return true;\n }\n var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;\n return typeof Ctor == 'function' && Ctor instanceof Ctor &&\n funcToString.call(Ctor) == objectCtorString;\n }\n\n /**\n * Checks if `value` is classified as a `RegExp` object.\n *\n * @static\n * @memberOf _\n * @since 0.1.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\n var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;\n\n /**\n * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754\n * double precision number which isn't the result of a rounded unsafe integer.\n *\n * **Note:** This method is based on\n * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.\n * @example\n *\n * _.isSafeInteger(3);\n * // => true\n *\n * _.isSafeInteger(Number.MIN_VALUE);\n * // => false\n *\n * _.isSafeInteger(Infinity);\n * // => false\n *\n * _.isSafeInteger('3');\n * // => false\n */\n function isSafeInteger(value) {\n return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is classified as a `Set` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a set, else `false`.\n * @example\n *\n * _.isSet(new Set);\n * // => true\n *\n * _.isSet(new WeakSet);\n * // => false\n */\n var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;\n\n /**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a string, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\n function isString(value) {\n return typeof value == 'string' ||\n (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);\n }\n\n /**\n * Checks if `value` is classified as a `Symbol` primitive or object.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.\n * @example\n *\n * _.isSymbol(Symbol.iterator);\n * // => true\n *\n * _.isSymbol('abc');\n * // => false\n */\n function isSymbol(value) {\n return typeof value == 'symbol' ||\n (isObjectLike(value) && baseGetTag(value) == symbolTag);\n }\n\n /**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\n var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;\n\n /**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\n function isUndefined(value) {\n return value === undefined;\n }\n\n /**\n * Checks if `value` is classified as a `WeakMap` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.\n * @example\n *\n * _.isWeakMap(new WeakMap);\n * // => true\n *\n * _.isWeakMap(new Map);\n * // => false\n */\n function isWeakMap(value) {\n return isObjectLike(value) && getTag(value) == weakMapTag;\n }\n\n /**\n * Checks if `value` is classified as a `WeakSet` object.\n *\n * @static\n * @memberOf _\n * @since 4.3.0\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.\n * @example\n *\n * _.isWeakSet(new WeakSet);\n * // => true\n *\n * _.isWeakSet(new Set);\n * // => false\n */\n function isWeakSet(value) {\n return isObjectLike(value) && baseGetTag(value) == weakSetTag;\n }\n\n /**\n * Checks if `value` is less than `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than `other`,\n * else `false`.\n * @see _.gt\n * @example\n *\n * _.lt(1, 3);\n * // => true\n *\n * _.lt(3, 3);\n * // => false\n *\n * _.lt(3, 1);\n * // => false\n */\n var lt = createRelationalOperation(baseLt);\n\n /**\n * Checks if `value` is less than or equal to `other`.\n *\n * @static\n * @memberOf _\n * @since 3.9.0\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @returns {boolean} Returns `true` if `value` is less than or equal to\n * `other`, else `false`.\n * @see _.gte\n * @example\n *\n * _.lte(1, 3);\n * // => true\n *\n * _.lte(3, 3);\n * // => true\n *\n * _.lte(3, 1);\n * // => false\n */\n var lte = createRelationalOperation(function(value, other) {\n return value <= other;\n });\n\n /**\n * Converts `value` to an array.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Array} Returns the converted array.\n * @example\n *\n * _.toArray({ 'a': 1, 'b': 2 });\n * // => [1, 2]\n *\n * _.toArray('abc');\n * // => ['a', 'b', 'c']\n *\n * _.toArray(1);\n * // => []\n *\n * _.toArray(null);\n * // => []\n */\n function toArray(value) {\n if (!value) {\n return [];\n }\n if (isArrayLike(value)) {\n return isString(value) ? stringToArray(value) : copyArray(value);\n }\n if (symIterator && value[symIterator]) {\n return iteratorToArray(value[symIterator]());\n }\n var tag = getTag(value),\n func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);\n\n return func(value);\n }\n\n /**\n * Converts `value` to a finite number.\n *\n * @static\n * @memberOf _\n * @since 4.12.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted number.\n * @example\n *\n * _.toFinite(3.2);\n * // => 3.2\n *\n * _.toFinite(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toFinite(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toFinite('3.2');\n * // => 3.2\n */\n function toFinite(value) {\n if (!value) {\n return value === 0 ? value : 0;\n }\n value = toNumber(value);\n if (value === INFINITY || value === -INFINITY) {\n var sign = (value < 0 ? -1 : 1);\n return sign * MAX_INTEGER;\n }\n return value === value ? value : 0;\n }\n\n /**\n * Converts `value` to an integer.\n *\n * **Note:** This method is loosely based on\n * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toInteger(3.2);\n * // => 3\n *\n * _.toInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toInteger(Infinity);\n * // => 1.7976931348623157e+308\n *\n * _.toInteger('3.2');\n * // => 3\n */\n function toInteger(value) {\n var result = toFinite(value),\n remainder = result % 1;\n\n return result === result ? (remainder ? result - remainder : result) : 0;\n }\n\n /**\n * Converts `value` to an integer suitable for use as the length of an\n * array-like object.\n *\n * **Note:** This method is based on\n * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toLength(3.2);\n * // => 3\n *\n * _.toLength(Number.MIN_VALUE);\n * // => 0\n *\n * _.toLength(Infinity);\n * // => 4294967295\n *\n * _.toLength('3.2');\n * // => 3\n */\n function toLength(value) {\n return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;\n }\n\n /**\n * Converts `value` to a number.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to process.\n * @returns {number} Returns the number.\n * @example\n *\n * _.toNumber(3.2);\n * // => 3.2\n *\n * _.toNumber(Number.MIN_VALUE);\n * // => 5e-324\n *\n * _.toNumber(Infinity);\n * // => Infinity\n *\n * _.toNumber('3.2');\n * // => 3.2\n */\n function toNumber(value) {\n if (typeof value == 'number') {\n return value;\n }\n if (isSymbol(value)) {\n return NAN;\n }\n if (isObject(value)) {\n var other = typeof value.valueOf == 'function' ? value.valueOf() : value;\n value = isObject(other) ? (other + '') : other;\n }\n if (typeof value != 'string') {\n return value === 0 ? value : +value;\n }\n value = value.replace(reTrim, '');\n var isBinary = reIsBinary.test(value);\n return (isBinary || reIsOctal.test(value))\n ? freeParseInt(value.slice(2), isBinary ? 2 : 8)\n : (reIsBadHex.test(value) ? NAN : +value);\n }\n\n /**\n * Converts `value` to a plain object flattening inherited enumerable string\n * keyed properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\n function toPlainObject(value) {\n return copyObject(value, keysIn(value));\n }\n\n /**\n * Converts `value` to a safe integer. A safe integer can be compared and\n * represented correctly.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.toSafeInteger(3.2);\n * // => 3\n *\n * _.toSafeInteger(Number.MIN_VALUE);\n * // => 0\n *\n * _.toSafeInteger(Infinity);\n * // => 9007199254740991\n *\n * _.toSafeInteger('3.2');\n * // => 3\n */\n function toSafeInteger(value) {\n return value\n ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)\n : (value === 0 ? value : 0);\n }\n\n /**\n * Converts `value` to a string. An empty string is returned for `null`\n * and `undefined` values. The sign of `-0` is preserved.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.toString(null);\n * // => ''\n *\n * _.toString(-0);\n * // => '-0'\n *\n * _.toString([1, 2, 3]);\n * // => '1,2,3'\n */\n function toString(value) {\n return value == null ? '' : baseToString(value);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Assigns own enumerable string keyed properties of source objects to the\n * destination object. Source objects are applied from left to right.\n * Subsequent sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object` and is loosely based on\n * [`Object.assign`](https://mdn.io/Object/assign).\n *\n * @static\n * @memberOf _\n * @since 0.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assignIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assign({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'c': 3 }\n */\n var assign = createAssigner(function(object, source) {\n if (isPrototype(source) || isArrayLike(source)) {\n copyObject(source, keys(source), object);\n return;\n }\n for (var key in source) {\n if (hasOwnProperty.call(source, key)) {\n assignValue(object, key, source[key]);\n }\n }\n });\n\n /**\n * This method is like `_.assign` except that it iterates over own and\n * inherited source properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extend\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.assign\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * function Bar() {\n * this.c = 3;\n * }\n *\n * Foo.prototype.b = 2;\n * Bar.prototype.d = 4;\n *\n * _.assignIn({ 'a': 0 }, new Foo, new Bar);\n * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }\n */\n var assignIn = createAssigner(function(object, source) {\n copyObject(source, keysIn(source), object);\n });\n\n /**\n * This method is like `_.assignIn` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias extendWith\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignInWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keysIn(source), object, customizer);\n });\n\n /**\n * This method is like `_.assign` except that it accepts `customizer`\n * which is invoked to produce the assigned values. If `customizer` returns\n * `undefined`, assignment is handled by the method instead. The `customizer`\n * is invoked with five arguments: (objValue, srcValue, key, object, source).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @see _.assignInWith\n * @example\n *\n * function customizer(objValue, srcValue) {\n * return _.isUndefined(objValue) ? srcValue : objValue;\n * }\n *\n * var defaults = _.partialRight(_.assignWith, customizer);\n *\n * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var assignWith = createAssigner(function(object, source, srcIndex, customizer) {\n copyObject(source, keys(source), object, customizer);\n });\n\n /**\n * Creates an array of values corresponding to `paths` of `object`.\n *\n * @static\n * @memberOf _\n * @since 1.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Array} Returns the picked values.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };\n *\n * _.at(object, ['a[0].b.c', 'a[1]']);\n * // => [3, 4]\n */\n var at = flatRest(baseAt);\n\n /**\n * Creates an object that inherits from the `prototype` object. If a\n * `properties` object is given, its own enumerable string keyed properties\n * are assigned to the created object.\n *\n * @static\n * @memberOf _\n * @since 2.3.0\n * @category Object\n * @param {Object} prototype The object to inherit from.\n * @param {Object} [properties] The properties to assign to the object.\n * @returns {Object} Returns the new object.\n * @example\n *\n * function Shape() {\n * this.x = 0;\n * this.y = 0;\n * }\n *\n * function Circle() {\n * Shape.call(this);\n * }\n *\n * Circle.prototype = _.create(Shape.prototype, {\n * 'constructor': Circle\n * });\n *\n * var circle = new Circle;\n * circle instanceof Circle;\n * // => true\n *\n * circle instanceof Shape;\n * // => true\n */\n function create(prototype, properties) {\n var result = baseCreate(prototype);\n return properties == null ? result : baseAssign(result, properties);\n }\n\n /**\n * Assigns own and inherited enumerable string keyed properties of source\n * objects to the destination object for all destination properties that\n * resolve to `undefined`. Source objects are applied from left to right.\n * Once a property is set, additional values of the same property are ignored.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaultsDeep\n * @example\n *\n * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });\n * // => { 'a': 1, 'b': 2 }\n */\n var defaults = baseRest(function(object, sources) {\n object = Object(object);\n\n var index = -1;\n var length = sources.length;\n var guard = length > 2 ? sources[2] : undefined;\n\n if (guard && isIterateeCall(sources[0], sources[1], guard)) {\n length = 1;\n }\n\n while (++index < length) {\n var source = sources[index];\n var props = keysIn(source);\n var propsIndex = -1;\n var propsLength = props.length;\n\n while (++propsIndex < propsLength) {\n var key = props[propsIndex];\n var value = object[key];\n\n if (value === undefined ||\n (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {\n object[key] = source[key];\n }\n }\n }\n\n return object;\n });\n\n /**\n * This method is like `_.defaults` except that it recursively assigns\n * default properties.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.10.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @see _.defaults\n * @example\n *\n * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });\n * // => { 'a': { 'b': 2, 'c': 3 } }\n */\n var defaultsDeep = baseRest(function(args) {\n args.push(undefined, customDefaultsMerge);\n return apply(mergeWith, undefined, args);\n });\n\n /**\n * This method is like `_.find` except that it returns the key of the first\n * element `predicate` returns truthy for instead of the element itself.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findKey(users, function(o) { return o.age < 40; });\n * // => 'barney' (iteration order is not guaranteed)\n *\n * // The `_.matches` iteratee shorthand.\n * _.findKey(users, { 'age': 1, 'active': true });\n * // => 'pebbles'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findKey(users, 'active');\n * // => 'barney'\n */\n function findKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);\n }\n\n /**\n * This method is like `_.findKey` except that it iterates over elements of\n * a collection in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {Function} [predicate=_.identity] The function invoked per iteration.\n * @returns {string|undefined} Returns the key of the matched element,\n * else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findLastKey(users, function(o) { return o.age < 40; });\n * // => returns 'pebbles' assuming `_.findKey` returns 'barney'\n *\n * // The `_.matches` iteratee shorthand.\n * _.findLastKey(users, { 'age': 36, 'active': true });\n * // => 'barney'\n *\n * // The `_.matchesProperty` iteratee shorthand.\n * _.findLastKey(users, ['active', false]);\n * // => 'fred'\n *\n * // The `_.property` iteratee shorthand.\n * _.findLastKey(users, 'active');\n * // => 'pebbles'\n */\n function findLastKey(object, predicate) {\n return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);\n }\n\n /**\n * Iterates over own and inherited enumerable string keyed properties of an\n * object and invokes `iteratee` for each property. The iteratee is invoked\n * with three arguments: (value, key, object). Iteratee functions may exit\n * iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forInRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forIn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).\n */\n function forIn(object, iteratee) {\n return object == null\n ? object\n : baseFor(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * This method is like `_.forIn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forIn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forInRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.\n */\n function forInRight(object, iteratee) {\n return object == null\n ? object\n : baseForRight(object, getIteratee(iteratee, 3), keysIn);\n }\n\n /**\n * Iterates over own enumerable string keyed properties of an object and\n * invokes `iteratee` for each property. The iteratee is invoked with three\n * arguments: (value, key, object). Iteratee functions may exit iteration\n * early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 0.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwnRight\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'a' then 'b' (iteration order is not guaranteed).\n */\n function forOwn(object, iteratee) {\n return object && baseForOwn(object, getIteratee(iteratee, 3));\n }\n\n /**\n * This method is like `_.forOwn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @since 2.0.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns `object`.\n * @see _.forOwn\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwnRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.\n */\n function forOwnRight(object, iteratee) {\n return object && baseForOwnRight(object, getIteratee(iteratee, 3));\n }\n\n /**\n * Creates an array of function property names from own enumerable properties\n * of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functionsIn\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functions(new Foo);\n * // => ['a', 'b']\n */\n function functions(object) {\n return object == null ? [] : baseFunctions(object, keys(object));\n }\n\n /**\n * Creates an array of function property names from own and inherited\n * enumerable properties of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the function names.\n * @see _.functions\n * @example\n *\n * function Foo() {\n * this.a = _.constant('a');\n * this.b = _.constant('b');\n * }\n *\n * Foo.prototype.c = _.constant('c');\n *\n * _.functionsIn(new Foo);\n * // => ['a', 'b', 'c']\n */\n function functionsIn(object) {\n return object == null ? [] : baseFunctions(object, keysIn(object));\n }\n\n /**\n * Gets the value at `path` of `object`. If the resolved value is\n * `undefined`, the `defaultValue` is returned in its place.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to get.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.get(object, 'a[0].b.c');\n * // => 3\n *\n * _.get(object, ['a', '0', 'b', 'c']);\n * // => 3\n *\n * _.get(object, 'a.b.c', 'default');\n * // => 'default'\n */\n function get(object, path, defaultValue) {\n var result = object == null ? undefined : baseGet(object, path);\n return result === undefined ? defaultValue : result;\n }\n\n /**\n * Checks if `path` is a direct property of `object`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = { 'a': { 'b': 2 } };\n * var other = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.has(object, 'a');\n * // => true\n *\n * _.has(object, 'a.b');\n * // => true\n *\n * _.has(object, ['a', 'b']);\n * // => true\n *\n * _.has(other, 'a');\n * // => false\n */\n function has(object, path) {\n return object != null && hasPath(object, path, baseHas);\n }\n\n /**\n * Checks if `path` is a direct or inherited property of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path to check.\n * @returns {boolean} Returns `true` if `path` exists, else `false`.\n * @example\n *\n * var object = _.create({ 'a': _.create({ 'b': 2 }) });\n *\n * _.hasIn(object, 'a');\n * // => true\n *\n * _.hasIn(object, 'a.b');\n * // => true\n *\n * _.hasIn(object, ['a', 'b']);\n * // => true\n *\n * _.hasIn(object, 'b');\n * // => false\n */\n function hasIn(object, path) {\n return object != null && hasPath(object, path, baseHasIn);\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite\n * property assignments of previous values.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Object\n * @param {Object} object The object to invert.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n */\n var invert = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n result[value] = key;\n }, constant(identity));\n\n /**\n * This method is like `_.invert` except that the inverted object is generated\n * from the results of running each element of `object` thru `iteratee`. The\n * corresponding inverted value of each inverted key is an array of keys\n * responsible for generating the inverted value. The iteratee is invoked\n * with one argument: (value).\n *\n * @static\n * @memberOf _\n * @since 4.1.0\n * @category Object\n * @param {Object} object The object to invert.\n * @param {Function} [iteratee=_.identity] The iteratee invoked per element.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invertBy(object);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n *\n * _.invertBy(object, function(value) {\n * return 'group' + value;\n * });\n * // => { 'group1': ['a', 'c'], 'group2': ['b'] }\n */\n var invertBy = createInverter(function(result, value, key) {\n if (value != null &&\n typeof value.toString != 'function') {\n value = nativeObjectToString.call(value);\n }\n\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }, getIteratee);\n\n /**\n * Invokes the method at `path` of `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the method to invoke.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {*} Returns the result of the invoked method.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };\n *\n * _.invoke(object, 'a[0].b.c.slice', 1, 3);\n * // => [2, 3]\n */\n var invoke = baseRest(baseInvoke);\n\n /**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)\n * for more details.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\n function keys(object) {\n return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);\n }\n\n /**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\n function keysIn(object) {\n return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);\n }\n\n /**\n * The opposite of `_.mapValues`; this method creates an object with the\n * same values as `object` and keys generated by running each own enumerable\n * string keyed property of `object` thru `iteratee`. The iteratee is invoked\n * with three arguments: (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 3.8.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapValues\n * @example\n *\n * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {\n * return key + value;\n * });\n * // => { 'a1': 1, 'b2': 2 }\n */\n function mapKeys(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, iteratee(value, key, object), value);\n });\n return result;\n }\n\n /**\n * Creates an object with the same keys as `object` and values generated\n * by running each own enumerable string keyed property of `object` thru\n * `iteratee`. The iteratee is invoked with three arguments:\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @since 2.4.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @returns {Object} Returns the new mapped object.\n * @see _.mapKeys\n * @example\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * _.mapValues(users, function(o) { return o.age; });\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n *\n * // The `_.property` iteratee shorthand.\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\n function mapValues(object, iteratee) {\n var result = {};\n iteratee = getIteratee(iteratee, 3);\n\n baseForOwn(object, function(value, key, object) {\n baseAssignValue(result, key, iteratee(value, key, object));\n });\n return result;\n }\n\n /**\n * This method is like `_.assign` except that it recursively merges own and\n * inherited enumerable string keyed properties of source objects into the\n * destination object. Source properties that resolve to `undefined` are\n * skipped if a destination value exists. Array and plain object properties\n * are merged recursively. Other objects and value types are overridden by\n * assignment. Source objects are applied from left to right. Subsequent\n * sources overwrite property assignments of previous sources.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 0.5.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {\n * 'a': [{ 'b': 2 }, { 'd': 4 }]\n * };\n *\n * var other = {\n * 'a': [{ 'c': 3 }, { 'e': 5 }]\n * };\n *\n * _.merge(object, other);\n * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }\n */\n var merge = createAssigner(function(object, source, srcIndex) {\n baseMerge(object, source, srcIndex);\n });\n\n /**\n * This method is like `_.merge` except that it accepts `customizer` which\n * is invoked to produce the merged values of the destination and source\n * properties. If `customizer` returns `undefined`, merging is handled by the\n * method instead. The `customizer` is invoked with six arguments:\n * (objValue, srcValue, key, object, source, stack).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} sources The source objects.\n * @param {Function} customizer The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function customizer(objValue, srcValue) {\n * if (_.isArray(objValue)) {\n * return objValue.concat(srcValue);\n * }\n * }\n *\n * var object = { 'a': [1], 'b': [2] };\n * var other = { 'a': [3], 'b': [4] };\n *\n * _.mergeWith(object, other, customizer);\n * // => { 'a': [1, 3], 'b': [2, 4] }\n */\n var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {\n baseMerge(object, source, srcIndex, customizer);\n });\n\n /**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable property paths of `object` that are not omitted.\n *\n * **Note:** This method is considerably slower than `_.pick`.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to omit.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omit(object, ['a', 'c']);\n * // => { 'b': '2' }\n */\n var omit = flatRest(function(object, paths) {\n var result = {};\n if (object == null) {\n return result;\n }\n var isDeep = false;\n paths = arrayMap(paths, function(path) {\n path = castPath(path, object);\n isDeep || (isDeep = path.length > 1);\n return path;\n });\n copyObject(object, getAllKeysIn(object), result);\n if (isDeep) {\n result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);\n }\n var length = paths.length;\n while (length--) {\n baseUnset(result, paths[length]);\n }\n return result;\n });\n\n /**\n * The opposite of `_.pickBy`; this method creates an object composed of\n * the own and inherited enumerable string keyed properties of `object` that\n * `predicate` doesn't return truthy for. The predicate is invoked with two\n * arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.omitBy(object, _.isNumber);\n * // => { 'b': '2' }\n */\n function omitBy(object, predicate) {\n return pickBy(object, negate(getIteratee(predicate)));\n }\n\n /**\n * Creates an object composed of the picked `object` properties.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {...(string|string[])} [paths] The property paths to pick.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pick(object, ['a', 'c']);\n * // => { 'a': 1, 'c': 3 }\n */\n var pick = flatRest(function(object, paths) {\n return object == null ? {} : basePick(object, paths);\n });\n\n /**\n * Creates an object composed of the `object` properties `predicate` returns\n * truthy for. The predicate is invoked with two arguments: (value, key).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The source object.\n * @param {Function} [predicate=_.identity] The function invoked per property.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'a': 1, 'b': '2', 'c': 3 };\n *\n * _.pickBy(object, _.isNumber);\n * // => { 'a': 1, 'c': 3 }\n */\n function pickBy(object, predicate) {\n if (object == null) {\n return {};\n }\n var props = arrayMap(getAllKeysIn(object), function(prop) {\n return [prop];\n });\n predicate = getIteratee(predicate);\n return basePickBy(object, props, function(value, path) {\n return predicate(value, path[0]);\n });\n }\n\n /**\n * This method is like `_.get` except that if the resolved value is a\n * function it's invoked with the `this` binding of its parent object and\n * its result is returned.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {Array|string} path The path of the property to resolve.\n * @param {*} [defaultValue] The value returned for `undefined` resolved values.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };\n *\n * _.result(object, 'a[0].b.c1');\n * // => 3\n *\n * _.result(object, 'a[0].b.c2');\n * // => 4\n *\n * _.result(object, 'a[0].b.c3', 'default');\n * // => 'default'\n *\n * _.result(object, 'a[0].b.c3', _.constant('default'));\n * // => 'default'\n */\n function result(object, path, defaultValue) {\n path = castPath(path, object);\n\n var index = -1,\n length = path.length;\n\n // Ensure the loop is entered when path is empty.\n if (!length) {\n length = 1;\n object = undefined;\n }\n while (++index < length) {\n var value = object == null ? undefined : object[toKey(path[index])];\n if (value === undefined) {\n index = length;\n value = defaultValue;\n }\n object = isFunction(value) ? value.call(object) : value;\n }\n return object;\n }\n\n /**\n * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,\n * it's created. Arrays are created for missing index properties while objects\n * are created for all other missing properties. Use `_.setWith` to customize\n * `path` creation.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 3.7.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.set(object, 'a[0].b.c', 4);\n * console.log(object.a[0].b.c);\n * // => 4\n *\n * _.set(object, ['x', '0', 'y', 'z'], 5);\n * console.log(object.x[0].y.z);\n * // => 5\n */\n function set(object, path, value) {\n return object == null ? object : baseSet(object, path, value);\n }\n\n /**\n * This method is like `_.set` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {*} value The value to set.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.setWith(object, '[0][1]', 'a', Object);\n * // => { '0': { '1': 'a' } }\n */\n function setWith(object, path, value, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseSet(object, path, value, customizer);\n }\n\n /**\n * Creates an array of own enumerable string keyed-value pairs for `object`\n * which can be consumed by `_.fromPairs`. If `object` is a map or set, its\n * entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entries\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairs(new Foo);\n * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)\n */\n var toPairs = createToPairs(keys);\n\n /**\n * Creates an array of own and inherited enumerable string keyed-value pairs\n * for `object` which can be consumed by `_.fromPairs`. If `object` is a map\n * or set, its entries are returned.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @alias entriesIn\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the key-value pairs.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.toPairsIn(new Foo);\n * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)\n */\n var toPairsIn = createToPairs(keysIn);\n\n /**\n * An alternative to `_.reduce`; this method transforms `object` to a new\n * `accumulator` object which is the result of running each of its own\n * enumerable string keyed properties thru `iteratee`, with each invocation\n * potentially mutating the `accumulator` object. If `accumulator` is not\n * provided, a new object with the same `[[Prototype]]` will be used. The\n * iteratee is invoked with four arguments: (accumulator, value, key, object).\n * Iteratee functions may exit iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @since 1.3.0\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The custom accumulator value.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.transform([2, 3, 4], function(result, n) {\n * result.push(n *= n);\n * return n % 2 == 0;\n * }, []);\n * // => [4, 9]\n *\n * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {\n * (result[value] || (result[value] = [])).push(key);\n * }, {});\n * // => { '1': ['a', 'c'], '2': ['b'] }\n */\n function transform(object, iteratee, accumulator) {\n var isArr = isArray(object),\n isArrLike = isArr || isBuffer(object) || isTypedArray(object);\n\n iteratee = getIteratee(iteratee, 4);\n if (accumulator == null) {\n var Ctor = object && object.constructor;\n if (isArrLike) {\n accumulator = isArr ? new Ctor : [];\n }\n else if (isObject(object)) {\n accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};\n }\n else {\n accumulator = {};\n }\n }\n (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {\n return iteratee(accumulator, value, index, object);\n });\n return accumulator;\n }\n\n /**\n * Removes the property at `path` of `object`.\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to unset.\n * @returns {boolean} Returns `true` if the property is deleted, else `false`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 7 } }] };\n * _.unset(object, 'a[0].b.c');\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n *\n * _.unset(object, ['a', '0', 'b', 'c']);\n * // => true\n *\n * console.log(object);\n * // => { 'a': [{ 'b': {} }] };\n */\n function unset(object, path) {\n return object == null ? true : baseUnset(object, path);\n }\n\n /**\n * This method is like `_.set` except that accepts `updater` to produce the\n * value to set. Use `_.updateWith` to customize `path` creation. The `updater`\n * is invoked with one argument: (value).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = { 'a': [{ 'b': { 'c': 3 } }] };\n *\n * _.update(object, 'a[0].b.c', function(n) { return n * n; });\n * console.log(object.a[0].b.c);\n * // => 9\n *\n * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });\n * console.log(object.x[0].y.z);\n * // => 0\n */\n function update(object, path, updater) {\n return object == null ? object : baseUpdate(object, path, castFunction(updater));\n }\n\n /**\n * This method is like `_.update` except that it accepts `customizer` which is\n * invoked to produce the objects of `path`. If `customizer` returns `undefined`\n * path creation is handled by the method instead. The `customizer` is invoked\n * with three arguments: (nsValue, key, nsObject).\n *\n * **Note:** This method mutates `object`.\n *\n * @static\n * @memberOf _\n * @since 4.6.0\n * @category Object\n * @param {Object} object The object to modify.\n * @param {Array|string} path The path of the property to set.\n * @param {Function} updater The function to produce the updated value.\n * @param {Function} [customizer] The function to customize assigned values.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var object = {};\n *\n * _.updateWith(object, '[0][1]', _.constant('a'), Object);\n * // => { '0': { '1': 'a' } }\n */\n function updateWith(object, path, updater, customizer) {\n customizer = typeof customizer == 'function' ? customizer : undefined;\n return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);\n }\n\n /**\n * Creates an array of the own enumerable string keyed property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\n function values(object) {\n return object == null ? [] : baseValues(object, keys(object));\n }\n\n /**\n * Creates an array of the own and inherited enumerable string keyed property\n * values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.valuesIn(new Foo);\n * // => [1, 2, 3] (iteration order is not guaranteed)\n */\n function valuesIn(object) {\n return object == null ? [] : baseValues(object, keysIn(object));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Clamps `number` within the inclusive `lower` and `upper` bounds.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category Number\n * @param {number} number The number to clamp.\n * @param {number} [lower] The lower bound.\n * @param {number} upper The upper bound.\n * @returns {number} Returns the clamped number.\n * @example\n *\n * _.clamp(-10, -5, 5);\n * // => -5\n *\n * _.clamp(10, -5, 5);\n * // => 5\n */\n function clamp(number, lower, upper) {\n if (upper === undefined) {\n upper = lower;\n lower = undefined;\n }\n if (upper !== undefined) {\n upper = toNumber(upper);\n upper = upper === upper ? upper : 0;\n }\n if (lower !== undefined) {\n lower = toNumber(lower);\n lower = lower === lower ? lower : 0;\n }\n return baseClamp(toNumber(number), lower, upper);\n }\n\n /**\n * Checks if `n` is between `start` and up to, but not including, `end`. If\n * `end` is not specified, it's set to `start` with `start` then set to `0`.\n * If `start` is greater than `end` the params are swapped to support\n * negative ranges.\n *\n * @static\n * @memberOf _\n * @since 3.3.0\n * @category Number\n * @param {number} number The number to check.\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `number` is in the range, else `false`.\n * @see _.range, _.rangeRight\n * @example\n *\n * _.inRange(3, 2, 4);\n * // => true\n *\n * _.inRange(4, 8);\n * // => true\n *\n * _.inRange(4, 2);\n * // => false\n *\n * _.inRange(2, 2);\n * // => false\n *\n * _.inRange(1.2, 2);\n * // => true\n *\n * _.inRange(5.2, 4);\n * // => false\n *\n * _.inRange(-3, -2, -6);\n * // => true\n */\n function inRange(number, start, end) {\n start = toFinite(start);\n if (end === undefined) {\n end = start;\n start = 0;\n } else {\n end = toFinite(end);\n }\n number = toNumber(number);\n return baseInRange(number, start, end);\n }\n\n /**\n * Produces a random number between the inclusive `lower` and `upper` bounds.\n * If only one argument is provided a number between `0` and the given number\n * is returned. If `floating` is `true`, or either `lower` or `upper` are\n * floats, a floating-point number is returned instead of an integer.\n *\n * **Note:** JavaScript follows the IEEE-754 standard for resolving\n * floating-point values which can produce unexpected results.\n *\n * @static\n * @memberOf _\n * @since 0.7.0\n * @category Number\n * @param {number} [lower=0] The lower bound.\n * @param {number} [upper=1] The upper bound.\n * @param {boolean} [floating] Specify returning a floating-point number.\n * @returns {number} Returns the random number.\n * @example\n *\n * _.random(0, 5);\n * // => an integer between 0 and 5\n *\n * _.random(5);\n * // => also an integer between 0 and 5\n *\n * _.random(5, true);\n * // => a floating-point number between 0 and 5\n *\n * _.random(1.2, 5.2);\n * // => a floating-point number between 1.2 and 5.2\n */\n function random(lower, upper, floating) {\n if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {\n upper = floating = undefined;\n }\n if (floating === undefined) {\n if (typeof upper == 'boolean') {\n floating = upper;\n upper = undefined;\n }\n else if (typeof lower == 'boolean') {\n floating = lower;\n lower = undefined;\n }\n }\n if (lower === undefined && upper === undefined) {\n lower = 0;\n upper = 1;\n }\n else {\n lower = toFinite(lower);\n if (upper === undefined) {\n upper = lower;\n lower = 0;\n } else {\n upper = toFinite(upper);\n }\n }\n if (lower > upper) {\n var temp = lower;\n lower = upper;\n upper = temp;\n }\n if (floating || lower % 1 || upper % 1) {\n var rand = nativeRandom();\n return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);\n }\n return baseRandom(lower, upper);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar--');\n * // => 'fooBar'\n *\n * _.camelCase('__FOO_BAR__');\n * // => 'fooBar'\n */\n var camelCase = createCompounder(function(result, word, index) {\n word = word.toLowerCase();\n return result + (index ? capitalize(word) : word);\n });\n\n /**\n * Converts the first character of `string` to upper case and the remaining\n * to lower case.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('FRED');\n * // => 'Fred'\n */\n function capitalize(string) {\n return upperFirst(toString(string).toLowerCase());\n }\n\n /**\n * Deburrs `string` by converting\n * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)\n * letters to basic Latin letters and removing\n * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('d\u00E9j\u00E0 vu');\n * // => 'deja vu'\n */\n function deburr(string) {\n string = toString(string);\n return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');\n }\n\n /**\n * Checks if `string` ends with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=string.length] The position to search up to.\n * @returns {boolean} Returns `true` if `string` ends with `target`,\n * else `false`.\n * @example\n *\n * _.endsWith('abc', 'c');\n * // => true\n *\n * _.endsWith('abc', 'b');\n * // => false\n *\n * _.endsWith('abc', 'b', 2);\n * // => true\n */\n function endsWith(string, target, position) {\n string = toString(string);\n target = baseToString(target);\n\n var length = string.length;\n position = position === undefined\n ? length\n : baseClamp(toInteger(position), 0, length);\n\n var end = position;\n position -= target.length;\n return position >= 0 && string.slice(position, end) == target;\n }\n\n /**\n * Converts the characters \"&\", \"<\", \">\", '\"', and \"'\" in `string` to their\n * corresponding HTML entities.\n *\n * **Note:** No other characters are escaped. To escape additional\n * characters use a third-party library like [_he_](https://mths.be/he).\n *\n * Though the \">\" character is escaped for symmetry, characters like\n * \">\" and \"/\" don't need escaping in HTML and have no special meaning\n * unless they're part of a tag or unquoted attribute value. See\n * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)\n * (under \"semi-related fun fact\") for more details.\n *\n * When working with HTML you should always\n * [quote attribute values](http://wonko.com/post/html-escaping) to reduce\n * XSS vectors.\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escape('fred, barney, & pebbles');\n * // => 'fred, barney, & pebbles'\n */\n function escape(string) {\n string = toString(string);\n return (string && reHasUnescapedHtml.test(string))\n ? string.replace(reUnescapedHtml, escapeHtmlChar)\n : string;\n }\n\n /**\n * Escapes the `RegExp` special characters \"^\", \"$\", \"\\\", \".\", \"*\", \"+\",\n * \"?\", \"(\", \")\", \"[\", \"]\", \"{\", \"}\", and \"|\" in `string`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escapeRegExp('[lodash](https://lodash.com/)');\n * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n */\n function escapeRegExp(string) {\n string = toString(string);\n return (string && reHasRegExpChar.test(string))\n ? string.replace(reRegExpChar, '\\\\$&')\n : string;\n }\n\n /**\n * Converts `string` to\n * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__FOO_BAR__');\n * // => 'foo-bar'\n */\n var kebabCase = createCompounder(function(result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n });\n\n /**\n * Converts `string`, as space separated words, to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the lower cased string.\n * @example\n *\n * _.lowerCase('--Foo-Bar--');\n * // => 'foo bar'\n *\n * _.lowerCase('fooBar');\n * // => 'foo bar'\n *\n * _.lowerCase('__FOO_BAR__');\n * // => 'foo bar'\n */\n var lowerCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + word.toLowerCase();\n });\n\n /**\n * Converts the first character of `string` to lower case.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the converted string.\n * @example\n *\n * _.lowerFirst('Fred');\n * // => 'fred'\n *\n * _.lowerFirst('FRED');\n * // => 'fRED'\n */\n var lowerFirst = createCaseFirst('toLowerCase');\n\n /**\n * Pads `string` on the left and right sides if it's shorter than `length`.\n * Padding characters are truncated if they can't be evenly divided by `length`.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.pad('abc', 8);\n * // => ' abc '\n *\n * _.pad('abc', 8, '_-');\n * // => '_-abc_-_'\n *\n * _.pad('abc', 3);\n * // => 'abc'\n */\n function pad(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n if (!length || strLength >= length) {\n return string;\n }\n var mid = (length - strLength) / 2;\n return (\n createPadding(nativeFloor(mid), chars) +\n string +\n createPadding(nativeCeil(mid), chars)\n );\n }\n\n /**\n * Pads `string` on the right side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padEnd('abc', 6);\n * // => 'abc '\n *\n * _.padEnd('abc', 6, '_-');\n * // => 'abc_-_'\n *\n * _.padEnd('abc', 3);\n * // => 'abc'\n */\n function padEnd(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (string + createPadding(length - strLength, chars))\n : string;\n }\n\n /**\n * Pads `string` on the left side if it's shorter than `length`. Padding\n * characters are truncated if they exceed `length`.\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padStart('abc', 6);\n * // => ' abc'\n *\n * _.padStart('abc', 6, '_-');\n * // => '_-_abc'\n *\n * _.padStart('abc', 3);\n * // => 'abc'\n */\n function padStart(string, length, chars) {\n string = toString(string);\n length = toInteger(length);\n\n var strLength = length ? stringSize(string) : 0;\n return (length && strLength < length)\n ? (createPadding(length - strLength, chars) + string)\n : string;\n }\n\n /**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a\n * hexadecimal, in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the\n * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.\n *\n * @static\n * @memberOf _\n * @since 1.1.0\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix=10] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\n function parseInt(string, radix, guard) {\n if (guard || radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);\n }\n\n /**\n * Repeats the given string `n` times.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to repeat.\n * @param {number} [n=1] The number of times to repeat the string.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {string} Returns the repeated string.\n * @example\n *\n * _.repeat('*', 3);\n * // => '***'\n *\n * _.repeat('abc', 2);\n * // => 'abcabc'\n *\n * _.repeat('abc', 0);\n * // => ''\n */\n function repeat(string, n, guard) {\n if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {\n n = 1;\n } else {\n n = toInteger(n);\n }\n return baseRepeat(toString(string), n);\n }\n\n /**\n * Replaces matches for `pattern` in `string` with `replacement`.\n *\n * **Note:** This method is based on\n * [`String#replace`](https://mdn.io/String/replace).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to modify.\n * @param {RegExp|string} pattern The pattern to replace.\n * @param {Function|string} replacement The match replacement.\n * @returns {string} Returns the modified string.\n * @example\n *\n * _.replace('Hi Fred', 'Fred', 'Barney');\n * // => 'Hi Barney'\n */\n function replace() {\n var args = arguments,\n string = toString(args[0]);\n\n return args.length < 3 ? string : string.replace(args[1], args[2]);\n }\n\n /**\n * Converts `string` to\n * [snake case](https://en.wikipedia.org/wiki/Snake_case).\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--FOO-BAR--');\n * // => 'foo_bar'\n */\n var snakeCase = createCompounder(function(result, word, index) {\n return result + (index ? '_' : '') + word.toLowerCase();\n });\n\n /**\n * Splits `string` by `separator`.\n *\n * **Note:** This method is based on\n * [`String#split`](https://mdn.io/String/split).\n *\n * @static\n * @memberOf _\n * @since 4.0.0\n * @category String\n * @param {string} [string=''] The string to split.\n * @param {RegExp|string} separator The separator pattern to split by.\n * @param {number} [limit] The length to truncate results to.\n * @returns {Array} Returns the string segments.\n * @example\n *\n * _.split('a-b-c', '-', 2);\n * // => ['a', 'b']\n */\n function split(string, separator, limit) {\n if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {\n separator = limit = undefined;\n }\n limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;\n if (!limit) {\n return [];\n }\n string = toString(string);\n if (string && (\n typeof separator == 'string' ||\n (separator != null && !isRegExp(separator))\n )) {\n separator = baseToString(separator);\n if (!separator && hasUnicode(string)) {\n return castSlice(stringToArray(string), 0, limit);\n }\n }\n return string.split(separator, limit);\n }\n\n /**\n * Converts `string` to\n * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).\n *\n * @static\n * @memberOf _\n * @since 3.1.0\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the start cased string.\n * @example\n *\n * _.startCase('--foo-bar--');\n * // => 'Foo Bar'\n *\n * _.startCase('fooBar');\n * // => 'Foo Bar'\n *\n * _.startCase('__FOO_BAR__');\n * // => 'FOO BAR'\n */\n var startCase = createCompounder(function(result, word, index) {\n return result + (index ? ' ' : '') + upperFirst(word);\n });\n\n /**\n * Checks if `string` starts with the given target string.\n *\n * @static\n * @memberOf _\n * @since 3.0.0\n * @category String\n * @param {string} [string=''] The string to inspect.\n * @param {string} [target] The string to search for.\n * @param {number} [position=0] The position to search from.\n * @returns {boolean} Returns `true` if `string` starts with `target`,\n * else `false`.\n * @example\n *\n * _.startsWith('abc', 'a');\n * // => true\n *\n * _.startsWith('abc', 'b');\n * // => false\n *\n * _.startsWith('abc', 'b', 1);\n * // => true\n */\n function startsWith(string, target, position) {\n string = toString(string);\n position = position == null\n ? 0\n : baseClamp(toInteger(position), 0, string.length);\n\n target = baseToString(target);\n return string.slice(position, position + target.length) == target;\n }\n\n /**\n * Creates a compiled template function that can interpolate data properties\n * in \"interpolate\" delimiters, HTML-escape interpolated data properties in\n * \"escape\" delimiters, and execute JavaScript in \"evaluate\" delimiters. Data\n * properties may be accessed as free variables in the template. If a setting\n * object is given, it takes precedence over `_.templateSettings` values.\n *\n * **Note:** In the development build `_.template` utilizes\n * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)\n * for easier debugging.\n *\n * For more information on precompiling templates see\n * [lodash's custom builds documentation](https://lodash.com/custom-builds).\n *\n * For more information on Chrome extension sandboxes see\n * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).\n *\n * @static\n * @since 0.1.0\n * @memberOf _\n * @category String\n * @param {string} [string=''] The template string.\n * @param {Object} [options={}] The options object.\n * @param {RegExp} [options.escape=_.templateSettings.escape]\n * The HTML \"escape\" delimiter.\n * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]\n * The \"evaluate\" delimiter.\n * @param {Object} [options.imports=_.templateSettings.imports]\n * An object to import into the template as free variables.\n * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]\n * The \"interpolate\" delimiter.\n * @param {string} [options.sourceURL='lodash.templateSources[n]']\n * The sourceURL of the compiled template.\n * @param {string} [options.variable='obj']\n * The data object variable name.\n * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.\n * @returns {Function} Returns the compiled template function.\n * @example\n *\n * // Use the \"interpolate\" delimiter to create a compiled template.\n * var compiled = _.template('hello <%= user %>!');\n * compiled({ 'user': 'fred' });\n * // => 'hello fred!'\n *\n * // Use the HTML \"escape\" delimiter to escape data property values.\n * var compiled = _.template('<%- value %>');\n * compiled({ 'value': '