repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
tadam313/sheet-db | src/rest_client.js | queryWorksheet | async function queryWorksheet(workSheetInfo, query, options) {
var key = util.createIdentifier(
workSheetInfo.worksheetId,
JSON.stringify(query)
);
options = options || {};
options.query = query;
return await fetchData(
key,
api.converter.queryResponse,
() => {
let payload = util._extend(
workSheetInfo,
api.converter.queryRequest(options)
);
return executeRequest('query_worksheet', payload);
});
} | javascript | async function queryWorksheet(workSheetInfo, query, options) {
var key = util.createIdentifier(
workSheetInfo.worksheetId,
JSON.stringify(query)
);
options = options || {};
options.query = query;
return await fetchData(
key,
api.converter.queryResponse,
() => {
let payload = util._extend(
workSheetInfo,
api.converter.queryRequest(options)
);
return executeRequest('query_worksheet', payload);
});
} | [
"async",
"function",
"queryWorksheet",
"(",
"workSheetInfo",
",",
"query",
",",
"options",
")",
"{",
"var",
"key",
"=",
"util",
".",
"createIdentifier",
"(",
"workSheetInfo",
".",
"worksheetId",
",",
"JSON",
".",
"stringify",
"(",
"query",
")",
")",
";",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"options",
".",
"query",
"=",
"query",
";",
"return",
"await",
"fetchData",
"(",
"key",
",",
"api",
".",
"converter",
".",
"queryResponse",
",",
"(",
")",
"=>",
"{",
"let",
"payload",
"=",
"util",
".",
"_extend",
"(",
"workSheetInfo",
",",
"api",
".",
"converter",
".",
"queryRequest",
"(",
"options",
")",
")",
";",
"return",
"executeRequest",
"(",
"'query_worksheet'",
",",
"payload",
")",
";",
"}",
")",
";",
"}"
] | Queries the specific worksheet
@param {object} workSheetInfo worksheetInfo SheetID and worksheetID
@param {object} query Query descriptor
@param {object} options query options | [
"Queries",
"the",
"specific",
"worksheet"
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L187-L207 | train |
tadam313/sheet-db | src/rest_client.js | deleteEntries | async function deleteEntries(worksheetInfo, entityIds) {
entityIds.reverse();
// since google pushes up the removed row, the ID will change to the previous
// avoiding this iterate through the collection in reverse order
// TODO: needs performance improvement
var response;
for (let id of entityIds) {
let payload = util._extend({entityId: id}, worksheetInfo);
response = await executeRequest('delete_entry', payload);
}
cache.clear();
return response;
} | javascript | async function deleteEntries(worksheetInfo, entityIds) {
entityIds.reverse();
// since google pushes up the removed row, the ID will change to the previous
// avoiding this iterate through the collection in reverse order
// TODO: needs performance improvement
var response;
for (let id of entityIds) {
let payload = util._extend({entityId: id}, worksheetInfo);
response = await executeRequest('delete_entry', payload);
}
cache.clear();
return response;
} | [
"async",
"function",
"deleteEntries",
"(",
"worksheetInfo",
",",
"entityIds",
")",
"{",
"entityIds",
".",
"reverse",
"(",
")",
";",
"var",
"response",
";",
"for",
"(",
"let",
"id",
"of",
"entityIds",
")",
"{",
"let",
"payload",
"=",
"util",
".",
"_extend",
"(",
"{",
"entityId",
":",
"id",
"}",
",",
"worksheetInfo",
")",
";",
"response",
"=",
"await",
"executeRequest",
"(",
"'delete_entry'",
",",
"payload",
")",
";",
"}",
"cache",
".",
"clear",
"(",
")",
";",
"return",
"response",
";",
"}"
] | Deletes specified entries
@param {object} worksheetInfo worksheetInfo SheetID and worksheetID
@param {array} entityIds IDs of the entities | [
"Deletes",
"specified",
"entries"
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L215-L231 | train |
tadam313/sheet-db | src/rest_client.js | queryFields | async function queryFields(workSheetInfo) {
var key = util.createIdentifier(
'queryFields',
workSheetInfo.worksheetId
);
return await fetchData(
key,
api.converter.queryFieldNames,
() => executeRequest('query_fields', workSheetInfo)
);
} | javascript | async function queryFields(workSheetInfo) {
var key = util.createIdentifier(
'queryFields',
workSheetInfo.worksheetId
);
return await fetchData(
key,
api.converter.queryFieldNames,
() => executeRequest('query_fields', workSheetInfo)
);
} | [
"async",
"function",
"queryFields",
"(",
"workSheetInfo",
")",
"{",
"var",
"key",
"=",
"util",
".",
"createIdentifier",
"(",
"'queryFields'",
",",
"workSheetInfo",
".",
"worksheetId",
")",
";",
"return",
"await",
"fetchData",
"(",
"key",
",",
"api",
".",
"converter",
".",
"queryFieldNames",
",",
"(",
")",
"=>",
"executeRequest",
"(",
"'query_fields'",
",",
"workSheetInfo",
")",
")",
";",
"}"
] | Queries the fields from the spreadsheet
@param {object} workSheetInfo SheetID and worksheetID | [
"Queries",
"the",
"fields",
"from",
"the",
"spreadsheet"
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/rest_client.js#L238-L249 | train |
tadam313/sheet-db | src/api/v3/converter.js | createXMLWriter | function createXMLWriter(extended) {
extended = extended || false;
var xw = new XmlWriter().startElement('entry')
.writeAttribute('xmlns', 'http://www.w3.org/2005/Atom');
return extended ?
xw.writeAttribute(
'xmlns:gsx',
'http://schemas.google.com/spreadsheets/2006/extended'
) :
xw.writeAttribute(
'xmlns:gs',
'http://schemas.google.com/spreadsheets/2006'
);
} | javascript | function createXMLWriter(extended) {
extended = extended || false;
var xw = new XmlWriter().startElement('entry')
.writeAttribute('xmlns', 'http://www.w3.org/2005/Atom');
return extended ?
xw.writeAttribute(
'xmlns:gsx',
'http://schemas.google.com/spreadsheets/2006/extended'
) :
xw.writeAttribute(
'xmlns:gs',
'http://schemas.google.com/spreadsheets/2006'
);
} | [
"function",
"createXMLWriter",
"(",
"extended",
")",
"{",
"extended",
"=",
"extended",
"||",
"false",
";",
"var",
"xw",
"=",
"new",
"XmlWriter",
"(",
")",
".",
"startElement",
"(",
"'entry'",
")",
".",
"writeAttribute",
"(",
"'xmlns'",
",",
"'http://www.w3.org/2005/Atom'",
")",
";",
"return",
"extended",
"?",
"xw",
".",
"writeAttribute",
"(",
"'xmlns:gsx'",
",",
"'http://schemas.google.com/spreadsheets/2006/extended'",
")",
":",
"xw",
".",
"writeAttribute",
"(",
"'xmlns:gs'",
",",
"'http://schemas.google.com/spreadsheets/2006'",
")",
";",
"}"
] | Creates XML writer for the data.
@param extended
@returns {*} | [
"Creates",
"XML",
"writer",
"for",
"the",
"data",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L28-L43 | train |
tadam313/sheet-db | src/api/v3/converter.js | queryRequest | function queryRequest(queryOptions) {
if (!queryOptions) {
return;
}
var options = util._extend({}, queryOptions);
if (options.query && options.query.length) {
options.query = '&sq=' + encodeURIComponent(options.query);
}
if (options.sort) {
options.orderBy = '&orderby=column:' + options.sort;
delete options.sort;
}
if (options.descending) {
options.reverse = '&reverse=true';
delete options.descending;
}
return options;
} | javascript | function queryRequest(queryOptions) {
if (!queryOptions) {
return;
}
var options = util._extend({}, queryOptions);
if (options.query && options.query.length) {
options.query = '&sq=' + encodeURIComponent(options.query);
}
if (options.sort) {
options.orderBy = '&orderby=column:' + options.sort;
delete options.sort;
}
if (options.descending) {
options.reverse = '&reverse=true';
delete options.descending;
}
return options;
} | [
"function",
"queryRequest",
"(",
"queryOptions",
")",
"{",
"if",
"(",
"!",
"queryOptions",
")",
"{",
"return",
";",
"}",
"var",
"options",
"=",
"util",
".",
"_extend",
"(",
"{",
"}",
",",
"queryOptions",
")",
";",
"if",
"(",
"options",
".",
"query",
"&&",
"options",
".",
"query",
".",
"length",
")",
"{",
"options",
".",
"query",
"=",
"'&sq='",
"+",
"encodeURIComponent",
"(",
"options",
".",
"query",
")",
";",
"}",
"if",
"(",
"options",
".",
"sort",
")",
"{",
"options",
".",
"orderBy",
"=",
"'&orderby=column:'",
"+",
"options",
".",
"sort",
";",
"delete",
"options",
".",
"sort",
";",
"}",
"if",
"(",
"options",
".",
"descending",
")",
"{",
"options",
".",
"reverse",
"=",
"'&reverse=true'",
";",
"delete",
"options",
".",
"descending",
";",
"}",
"return",
"options",
";",
"}"
] | Transforms query request object
@param queryOptions
@returns {*} | [
"Transforms",
"query",
"request",
"object"
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L61-L84 | train |
tadam313/sheet-db | src/api/v3/converter.js | worksheetData | function worksheetData(worksheet) {
return {
worksheetId: getItemIdFromUrl(g(worksheet.id)),
title: g(worksheet.title),
updated: g(worksheet.updated),
colCount: g(worksheet['gs$colCount']),
rowCount: g(worksheet['gs$rowCount'])
};
} | javascript | function worksheetData(worksheet) {
return {
worksheetId: getItemIdFromUrl(g(worksheet.id)),
title: g(worksheet.title),
updated: g(worksheet.updated),
colCount: g(worksheet['gs$colCount']),
rowCount: g(worksheet['gs$rowCount'])
};
} | [
"function",
"worksheetData",
"(",
"worksheet",
")",
"{",
"return",
"{",
"worksheetId",
":",
"getItemIdFromUrl",
"(",
"g",
"(",
"worksheet",
".",
"id",
")",
")",
",",
"title",
":",
"g",
"(",
"worksheet",
".",
"title",
")",
",",
"updated",
":",
"g",
"(",
"worksheet",
".",
"updated",
")",
",",
"colCount",
":",
"g",
"(",
"worksheet",
"[",
"'gs$colCount'",
"]",
")",
",",
"rowCount",
":",
"g",
"(",
"worksheet",
"[",
"'gs$rowCount'",
"]",
")",
"}",
";",
"}"
] | Converts 'worksheet info' response to domain specific data.
@param worksheet
@returns {{id: *, title, updated: Date, colCount, rowCount}} | [
"Converts",
"worksheet",
"info",
"response",
"to",
"domain",
"specific",
"data",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L92-L100 | train |
tadam313/sheet-db | src/api/v3/converter.js | worksheetEntry | function worksheetEntry(entry, fieldPrefix) {
fieldPrefix = fieldPrefix || 'gsx$';
var data = {
'_id': getItemIdFromUrl(g(entry.id)),
'_updated': g(entry.updated)
};
Object.keys(entry)
.filter(function(key) {
return ~key.indexOf(fieldPrefix) && g(entry[key], true);
})
.forEach(function(key) {
var normalizedKey = key.substr(fieldPrefix.length);
data[normalizedKey] = g(entry[key]);
});
return data;
} | javascript | function worksheetEntry(entry, fieldPrefix) {
fieldPrefix = fieldPrefix || 'gsx$';
var data = {
'_id': getItemIdFromUrl(g(entry.id)),
'_updated': g(entry.updated)
};
Object.keys(entry)
.filter(function(key) {
return ~key.indexOf(fieldPrefix) && g(entry[key], true);
})
.forEach(function(key) {
var normalizedKey = key.substr(fieldPrefix.length);
data[normalizedKey] = g(entry[key]);
});
return data;
} | [
"function",
"worksheetEntry",
"(",
"entry",
",",
"fieldPrefix",
")",
"{",
"fieldPrefix",
"=",
"fieldPrefix",
"||",
"'gsx$'",
";",
"var",
"data",
"=",
"{",
"'_id'",
":",
"getItemIdFromUrl",
"(",
"g",
"(",
"entry",
".",
"id",
")",
")",
",",
"'_updated'",
":",
"g",
"(",
"entry",
".",
"updated",
")",
"}",
";",
"Object",
".",
"keys",
"(",
"entry",
")",
".",
"filter",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"~",
"key",
".",
"indexOf",
"(",
"fieldPrefix",
")",
"&&",
"g",
"(",
"entry",
"[",
"key",
"]",
",",
"true",
")",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"var",
"normalizedKey",
"=",
"key",
".",
"substr",
"(",
"fieldPrefix",
".",
"length",
")",
";",
"data",
"[",
"normalizedKey",
"]",
"=",
"g",
"(",
"entry",
"[",
"key",
"]",
")",
";",
"}",
")",
";",
"return",
"data",
";",
"}"
] | Converts 'get worksheet entry' response to domain specific data.
@param entry
@param fieldPrefix
@returns {*} | [
"Converts",
"get",
"worksheet",
"entry",
"response",
"to",
"domain",
"specific",
"data",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L109-L127 | train |
tadam313/sheet-db | src/api/v3/converter.js | sheetInfoResponse | function sheetInfoResponse(rawData) {
var feed = rawData.feed;
return {
title: g(feed.title),
updated: g(feed.updated),
workSheets: feed.entry.map(worksheetData),
authors: feed.author.map(item => ({ name: g(item.name), email: g(item.email) }))
};
} | javascript | function sheetInfoResponse(rawData) {
var feed = rawData.feed;
return {
title: g(feed.title),
updated: g(feed.updated),
workSheets: feed.entry.map(worksheetData),
authors: feed.author.map(item => ({ name: g(item.name), email: g(item.email) }))
};
} | [
"function",
"sheetInfoResponse",
"(",
"rawData",
")",
"{",
"var",
"feed",
"=",
"rawData",
".",
"feed",
";",
"return",
"{",
"title",
":",
"g",
"(",
"feed",
".",
"title",
")",
",",
"updated",
":",
"g",
"(",
"feed",
".",
"updated",
")",
",",
"workSheets",
":",
"feed",
".",
"entry",
".",
"map",
"(",
"worksheetData",
")",
",",
"authors",
":",
"feed",
".",
"author",
".",
"map",
"(",
"item",
"=>",
"(",
"{",
"name",
":",
"g",
"(",
"item",
".",
"name",
")",
",",
"email",
":",
"g",
"(",
"item",
".",
"email",
")",
"}",
")",
")",
"}",
";",
"}"
] | Converts 'sheet info' response to domain specific data.
@param rawData
@returns {*} | [
"Converts",
"sheet",
"info",
"response",
"to",
"domain",
"specific",
"data",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L135-L144 | train |
tadam313/sheet-db | src/api/v3/converter.js | workSheetInfoResponse | function workSheetInfoResponse(rawData) {
if (typeof rawData === 'string') {
rawData = JSON.parse(rawData);
}
return worksheetData(rawData.entry);
} | javascript | function workSheetInfoResponse(rawData) {
if (typeof rawData === 'string') {
rawData = JSON.parse(rawData);
}
return worksheetData(rawData.entry);
} | [
"function",
"workSheetInfoResponse",
"(",
"rawData",
")",
"{",
"if",
"(",
"typeof",
"rawData",
"===",
"'string'",
")",
"{",
"rawData",
"=",
"JSON",
".",
"parse",
"(",
"rawData",
")",
";",
"}",
"return",
"worksheetData",
"(",
"rawData",
".",
"entry",
")",
";",
"}"
] | Converts create worksheet result to domain specific data.
@param rawData
@returns {*} | [
"Converts",
"create",
"worksheet",
"result",
"to",
"domain",
"specific",
"data",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L152-L159 | train |
tadam313/sheet-db | src/api/v3/converter.js | queryResponse | function queryResponse(rawData) {
var entry = rawData.feed.entry || [];
return entry.map(function(item) {
return worksheetEntry(item);
});
} | javascript | function queryResponse(rawData) {
var entry = rawData.feed.entry || [];
return entry.map(function(item) {
return worksheetEntry(item);
});
} | [
"function",
"queryResponse",
"(",
"rawData",
")",
"{",
"var",
"entry",
"=",
"rawData",
".",
"feed",
".",
"entry",
"||",
"[",
"]",
";",
"return",
"entry",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"return",
"worksheetEntry",
"(",
"item",
")",
";",
"}",
")",
";",
"}"
] | Converts the query results to domain specific data.
@param rawData
@returns {*} | [
"Converts",
"the",
"query",
"results",
"to",
"domain",
"specific",
"data",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L167-L172 | train |
tadam313/sheet-db | src/api/v3/converter.js | queryFieldNames | function queryFieldNames(rawData) {
var entry = rawData.feed.entry || [];
return entry.map(function(item) {
var field = worksheetEntry(item, 'gs$');
field.cell = field.cell.replace(/_/g, '');
return field;
});
} | javascript | function queryFieldNames(rawData) {
var entry = rawData.feed.entry || [];
return entry.map(function(item) {
var field = worksheetEntry(item, 'gs$');
field.cell = field.cell.replace(/_/g, '');
return field;
});
} | [
"function",
"queryFieldNames",
"(",
"rawData",
")",
"{",
"var",
"entry",
"=",
"rawData",
".",
"feed",
".",
"entry",
"||",
"[",
"]",
";",
"return",
"entry",
".",
"map",
"(",
"function",
"(",
"item",
")",
"{",
"var",
"field",
"=",
"worksheetEntry",
"(",
"item",
",",
"'gs$'",
")",
";",
"field",
".",
"cell",
"=",
"field",
".",
"cell",
".",
"replace",
"(",
"/",
"_",
"/",
"g",
",",
"''",
")",
";",
"return",
"field",
";",
"}",
")",
";",
"}"
] | Converts field names query response, used by schema operations
@param rawData | [
"Converts",
"field",
"names",
"query",
"response",
"used",
"by",
"schema",
"operations"
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L179-L186 | train |
tadam313/sheet-db | src/api/v3/converter.js | createWorksheetRequest | function createWorksheetRequest(options) {
options = options || {};
// TODO: needs to handle overflow cases and create ore dynamically
var rowCount = util.coerceNumber(options.rowCount || 5000);
var colCount = util.coerceNumber(options.colCount || 50);
options.rowCount = Math.max(rowCount, 10);
options.colCount = Math.max(colCount, 10);
var xw = createXMLWriter()
.startElement('title')
.text(options.title)
.endElement()
.startElement('gs:rowCount')
.text(options.rowCount)
.endElement()
.startElement('gs:colCount')
.text(options.colCount)
.endElement()
.endElement();
return xw.toString();
} | javascript | function createWorksheetRequest(options) {
options = options || {};
// TODO: needs to handle overflow cases and create ore dynamically
var rowCount = util.coerceNumber(options.rowCount || 5000);
var colCount = util.coerceNumber(options.colCount || 50);
options.rowCount = Math.max(rowCount, 10);
options.colCount = Math.max(colCount, 10);
var xw = createXMLWriter()
.startElement('title')
.text(options.title)
.endElement()
.startElement('gs:rowCount')
.text(options.rowCount)
.endElement()
.startElement('gs:colCount')
.text(options.colCount)
.endElement()
.endElement();
return xw.toString();
} | [
"function",
"createWorksheetRequest",
"(",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"var",
"rowCount",
"=",
"util",
".",
"coerceNumber",
"(",
"options",
".",
"rowCount",
"||",
"5000",
")",
";",
"var",
"colCount",
"=",
"util",
".",
"coerceNumber",
"(",
"options",
".",
"colCount",
"||",
"50",
")",
";",
"options",
".",
"rowCount",
"=",
"Math",
".",
"max",
"(",
"rowCount",
",",
"10",
")",
";",
"options",
".",
"colCount",
"=",
"Math",
".",
"max",
"(",
"colCount",
",",
"10",
")",
";",
"var",
"xw",
"=",
"createXMLWriter",
"(",
")",
".",
"startElement",
"(",
"'title'",
")",
".",
"text",
"(",
"options",
".",
"title",
")",
".",
"endElement",
"(",
")",
".",
"startElement",
"(",
"'gs:rowCount'",
")",
".",
"text",
"(",
"options",
".",
"rowCount",
")",
".",
"endElement",
"(",
")",
".",
"startElement",
"(",
"'gs:colCount'",
")",
".",
"text",
"(",
"options",
".",
"colCount",
")",
".",
"endElement",
"(",
")",
".",
"endElement",
"(",
")",
";",
"return",
"xw",
".",
"toString",
"(",
")",
";",
"}"
] | Creates worksheet request payload.
@param options
@returns {*} | [
"Creates",
"worksheet",
"request",
"payload",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L194-L217 | train |
tadam313/sheet-db | src/api/v3/converter.js | createEntryRequest | function createEntryRequest(entry) {
var xw = createXMLWriter(true);
Object.keys(entry).forEach(function(key) {
xw = xw.startElement('gsx:' + key)
.text(util.coerceNumber(entry[key]).toString())
.endElement();
});
return xw.endElement().toString();
} | javascript | function createEntryRequest(entry) {
var xw = createXMLWriter(true);
Object.keys(entry).forEach(function(key) {
xw = xw.startElement('gsx:' + key)
.text(util.coerceNumber(entry[key]).toString())
.endElement();
});
return xw.endElement().toString();
} | [
"function",
"createEntryRequest",
"(",
"entry",
")",
"{",
"var",
"xw",
"=",
"createXMLWriter",
"(",
"true",
")",
";",
"Object",
".",
"keys",
"(",
"entry",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"xw",
"=",
"xw",
".",
"startElement",
"(",
"'gsx:'",
"+",
"key",
")",
".",
"text",
"(",
"util",
".",
"coerceNumber",
"(",
"entry",
"[",
"key",
"]",
")",
".",
"toString",
"(",
")",
")",
".",
"endElement",
"(",
")",
";",
"}",
")",
";",
"return",
"xw",
".",
"endElement",
"(",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Creates 'create entry' request payload.
@param entry
@returns {*} | [
"Creates",
"create",
"entry",
"request",
"payload",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L225-L235 | train |
tadam313/sheet-db | src/api/v3/converter.js | updateEntryRequest | function updateEntryRequest(entry) {
var xw = createXMLWriter(true);
Object.keys(entry)
.filter(function(key) {
// filter out internal properties
return key.indexOf('_') !== 0;
})
.forEach(function(key) {
xw = xw.startElement('gsx:' + key)
.text(util.coerceNumber(entry[key]).toString())
.endElement();
});
return xw.endElement().toString();
} | javascript | function updateEntryRequest(entry) {
var xw = createXMLWriter(true);
Object.keys(entry)
.filter(function(key) {
// filter out internal properties
return key.indexOf('_') !== 0;
})
.forEach(function(key) {
xw = xw.startElement('gsx:' + key)
.text(util.coerceNumber(entry[key]).toString())
.endElement();
});
return xw.endElement().toString();
} | [
"function",
"updateEntryRequest",
"(",
"entry",
")",
"{",
"var",
"xw",
"=",
"createXMLWriter",
"(",
"true",
")",
";",
"Object",
".",
"keys",
"(",
"entry",
")",
".",
"filter",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"key",
".",
"indexOf",
"(",
"'_'",
")",
"!==",
"0",
";",
"}",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"xw",
"=",
"xw",
".",
"startElement",
"(",
"'gsx:'",
"+",
"key",
")",
".",
"text",
"(",
"util",
".",
"coerceNumber",
"(",
"entry",
"[",
"key",
"]",
")",
".",
"toString",
"(",
")",
")",
".",
"endElement",
"(",
")",
";",
"}",
")",
";",
"return",
"xw",
".",
"endElement",
"(",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Creates an 'update entry' request payload
@param entry
@returns {*} | [
"Creates",
"an",
"update",
"entry",
"request",
"payload"
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L243-L258 | train |
tadam313/sheet-db | src/api/v3/converter.js | createFieldRequest | function createFieldRequest(columnName, position) {
if (util.isNaN(position) || position <= 0) {
throw new TypeError('Position should be a number which is higher than one!');
}
var xw = createXMLWriter();
xw = xw.startElement('gs:cell')
.writeAttribute('row', 1)
.writeAttribute('col', position)
.writeAttribute('inputValue', columnName)
.endElement();
return xw.endElement().toString();
} | javascript | function createFieldRequest(columnName, position) {
if (util.isNaN(position) || position <= 0) {
throw new TypeError('Position should be a number which is higher than one!');
}
var xw = createXMLWriter();
xw = xw.startElement('gs:cell')
.writeAttribute('row', 1)
.writeAttribute('col', position)
.writeAttribute('inputValue', columnName)
.endElement();
return xw.endElement().toString();
} | [
"function",
"createFieldRequest",
"(",
"columnName",
",",
"position",
")",
"{",
"if",
"(",
"util",
".",
"isNaN",
"(",
"position",
")",
"||",
"position",
"<=",
"0",
")",
"{",
"throw",
"new",
"TypeError",
"(",
"'Position should be a number which is higher than one!'",
")",
";",
"}",
"var",
"xw",
"=",
"createXMLWriter",
"(",
")",
";",
"xw",
"=",
"xw",
".",
"startElement",
"(",
"'gs:cell'",
")",
".",
"writeAttribute",
"(",
"'row'",
",",
"1",
")",
".",
"writeAttribute",
"(",
"'col'",
",",
"position",
")",
".",
"writeAttribute",
"(",
"'inputValue'",
",",
"columnName",
")",
".",
"endElement",
"(",
")",
";",
"return",
"xw",
".",
"endElement",
"(",
")",
".",
"toString",
"(",
")",
";",
"}"
] | Creates the 'create column' request payload
@param columnName
@param position
@returns {*} | [
"Creates",
"the",
"create",
"column",
"request",
"payload"
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/api/v3/converter.js#L268-L283 | train |
doda/immutable-lodash | src/immutable-lodash.js | chunk | function chunk(iterable, size=1) {
let current = 0
if (_.isEmpty(iterable)) {
return iterable
}
let result = List()
while (current < iterable.size) {
result = result.push(iterable.slice(current, current + size))
current += size
}
return result
} | javascript | function chunk(iterable, size=1) {
let current = 0
if (_.isEmpty(iterable)) {
return iterable
}
let result = List()
while (current < iterable.size) {
result = result.push(iterable.slice(current, current + size))
current += size
}
return result
} | [
"function",
"chunk",
"(",
"iterable",
",",
"size",
"=",
"1",
")",
"{",
"let",
"current",
"=",
"0",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"iterable",
")",
")",
"{",
"return",
"iterable",
"}",
"let",
"result",
"=",
"List",
"(",
")",
"while",
"(",
"current",
"<",
"iterable",
".",
"size",
")",
"{",
"result",
"=",
"result",
".",
"push",
"(",
"iterable",
".",
"slice",
"(",
"current",
",",
"current",
"+",
"size",
")",
")",
"current",
"+=",
"size",
"}",
"return",
"result",
"}"
] | Creates an iterable of elements split into groups the length of `size`.
If `iterable` can't be split evenly, the final chunk will be the remaining
elements.
@static
@memberOf _
@category Iterable
@param {Iterable} iterable The iterable to process.
@param {number} [size=1] The length of each chunk
@returns {Iterable} Returns the new iterable of chunks.
@example
let list = ['a', 'b', 'c', 'd']
_.chunk(list, 2)
// => [['a', 'b'], ['c', 'd']]
_.chunk(list, 3)
// => [['a', 'b', 'c'], ['d']] | [
"Creates",
"an",
"iterable",
"of",
"elements",
"split",
"into",
"groups",
"the",
"length",
"of",
"size",
".",
"If",
"iterable",
"can",
"t",
"be",
"split",
"evenly",
"the",
"final",
"chunk",
"will",
"be",
"the",
"remaining",
"elements",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L46-L57 | train |
doda/immutable-lodash | src/immutable-lodash.js | difference | function difference(iterable, values) {
const valueSet = Set(values)
return iterable.filterNot((x) => valueSet.has(x))
} | javascript | function difference(iterable, values) {
const valueSet = Set(values)
return iterable.filterNot((x) => valueSet.has(x))
} | [
"function",
"difference",
"(",
"iterable",
",",
"values",
")",
"{",
"const",
"valueSet",
"=",
"Set",
"(",
"values",
")",
"return",
"iterable",
".",
"filterNot",
"(",
"(",
"x",
")",
"=>",
"valueSet",
".",
"has",
"(",
"x",
")",
")",
"}"
] | Creates an Iterable of `iterable` values not included in the other given iterables
The order of result values is determined by the order they occur
in the first iterable.
@static
@memberOf _
@category Iterable
@param {Iterable} iterable The iterable to inspect.
@param {...Iterable} [values] The values to exclude.
@returns {Iterable} Returns the iterable of filtered values.
@see _.without, _.xor
@example
_.difference([2, 1], [2, 3])
// => [1] | [
"Creates",
"an",
"Iterable",
"of",
"iterable",
"values",
"not",
"included",
"in",
"the",
"other",
"given",
"iterables",
"The",
"order",
"of",
"result",
"values",
"is",
"determined",
"by",
"the",
"order",
"they",
"occur",
"in",
"the",
"first",
"iterable",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L117-L120 | train |
doda/immutable-lodash | src/immutable-lodash.js | fill | function fill(iterable, value, start=0, end=iterable.size) {
let num = end - start
return iterable.splice(start, num, ...Repeat(value, num))
} | javascript | function fill(iterable, value, start=0, end=iterable.size) {
let num = end - start
return iterable.splice(start, num, ...Repeat(value, num))
} | [
"function",
"fill",
"(",
"iterable",
",",
"value",
",",
"start",
"=",
"0",
",",
"end",
"=",
"iterable",
".",
"size",
")",
"{",
"let",
"num",
"=",
"end",
"-",
"start",
"return",
"iterable",
".",
"splice",
"(",
"start",
",",
"num",
",",
"...",
"Repeat",
"(",
"value",
",",
"num",
")",
")",
"}"
] | Fills elements of `iterable` with `value` from `start` up to, but not
including, `end`.
@static
@memberOf _
@category Iterable
@param {Iterable} iterable The iterable to fill.
@param {*} value The value to fill `iterable` with.
@param {number} [start=0] The start position.
@param {number} [end=iterable.size] The end position.
@returns {Iterable} Returns `iterable`.
@example
let list = [1, 2, 3]
_.fill(list, 'a')
// => ['a', 'a', 'a']
_.fill([4, 6, 8, 10], '*', 1, 3)
// => [4, '*', '*', 10] | [
"Fills",
"elements",
"of",
"iterable",
"with",
"value",
"from",
"start",
"up",
"to",
"but",
"not",
"including",
"end",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L170-L173 | train |
doda/immutable-lodash | src/immutable-lodash.js | intersection | function intersection(...iterables) {
if (_.isEmpty(iterables)) return OrderedSet()
let result = OrderedSet(iterables[0])
for (let iterable of iterables.slice(1)) {
result = result.intersect(iterable)
}
return result.toSeq()
} | javascript | function intersection(...iterables) {
if (_.isEmpty(iterables)) return OrderedSet()
let result = OrderedSet(iterables[0])
for (let iterable of iterables.slice(1)) {
result = result.intersect(iterable)
}
return result.toSeq()
} | [
"function",
"intersection",
"(",
"...",
"iterables",
")",
"{",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"iterables",
")",
")",
"return",
"OrderedSet",
"(",
")",
"let",
"result",
"=",
"OrderedSet",
"(",
"iterables",
"[",
"0",
"]",
")",
"for",
"(",
"let",
"iterable",
"of",
"iterables",
".",
"slice",
"(",
"1",
")",
")",
"{",
"result",
"=",
"result",
".",
"intersect",
"(",
"iterable",
")",
"}",
"return",
"result",
".",
"toSeq",
"(",
")",
"}"
] | Returns a sequence of unique values that are included in all given iterables
The order of result values is determined by the order they occur in the first iterable.
@static
@memberOf _
@category Iterable
@param {...Iterable} [iterables] The iterables to inspect.
@returns {Iterable} Returns the new iterable of intersecting values.
@example
_.intersection([2, 1], [2, 3])
// => Seq [2] | [
"Returns",
"a",
"sequence",
"of",
"unique",
"values",
"that",
"are",
"included",
"in",
"all",
"given",
"iterables",
"The",
"order",
"of",
"result",
"values",
"is",
"determined",
"by",
"the",
"order",
"they",
"occur",
"in",
"the",
"first",
"iterable",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L190-L198 | train |
doda/immutable-lodash | src/immutable-lodash.js | sample | function sample(iterable) {
let index = lodash.random(0, iterable.size - 1)
return iterable.get(index)
} | javascript | function sample(iterable) {
let index = lodash.random(0, iterable.size - 1)
return iterable.get(index)
} | [
"function",
"sample",
"(",
"iterable",
")",
"{",
"let",
"index",
"=",
"lodash",
".",
"random",
"(",
"0",
",",
"iterable",
".",
"size",
"-",
"1",
")",
"return",
"iterable",
".",
"get",
"(",
"index",
")",
"}"
] | Gets a random element from `iterable`.
@static
@memberOf _
@category iterable
@param {Iterable} iterable The iterable to sample.
@returns {*} Returns the random element.
@example
_.sample([1, 2, 3, 4])
// => 2 | [
"Gets",
"a",
"random",
"element",
"from",
"iterable",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L515-L518 | train |
doda/immutable-lodash | src/immutable-lodash.js | sampleSize | function sampleSize(iterable, n=1) {
let index = -1
let result = List(iterable)
const length = result.size
const lastIndex = length - 1
while (++index < n) {
const rand = lodash.random(index, lastIndex)
const value = result.get(rand)
result = result.set(rand, result.get(index))
result = result.set(index, value)
}
return result.slice(0, Math.min(length, n))
} | javascript | function sampleSize(iterable, n=1) {
let index = -1
let result = List(iterable)
const length = result.size
const lastIndex = length - 1
while (++index < n) {
const rand = lodash.random(index, lastIndex)
const value = result.get(rand)
result = result.set(rand, result.get(index))
result = result.set(index, value)
}
return result.slice(0, Math.min(length, n))
} | [
"function",
"sampleSize",
"(",
"iterable",
",",
"n",
"=",
"1",
")",
"{",
"let",
"index",
"=",
"-",
"1",
"let",
"result",
"=",
"List",
"(",
"iterable",
")",
"const",
"length",
"=",
"result",
".",
"size",
"const",
"lastIndex",
"=",
"length",
"-",
"1",
"while",
"(",
"++",
"index",
"<",
"n",
")",
"{",
"const",
"rand",
"=",
"lodash",
".",
"random",
"(",
"index",
",",
"lastIndex",
")",
"const",
"value",
"=",
"result",
".",
"get",
"(",
"rand",
")",
"result",
"=",
"result",
".",
"set",
"(",
"rand",
",",
"result",
".",
"get",
"(",
"index",
")",
")",
"result",
"=",
"result",
".",
"set",
"(",
"index",
",",
"value",
")",
"}",
"return",
"result",
".",
"slice",
"(",
"0",
",",
"Math",
".",
"min",
"(",
"length",
",",
"n",
")",
")",
"}"
] | Gets `n` random elements at unique keys from `iterable` up to the
size of `iterable`.
@static
@memberOf _
@category iterable
@param {Iterable} iterable The iterable to sample.
@param {number} [n=1] The number of elements to sample.
@returns {List} Returns the random elements.
@example
_.sampleSize([1, 2, 3], 2)
// => List [3, 1]
_.sampleSize([1, 2, 3], 4)
// => List [2, 3, 1] | [
"Gets",
"n",
"random",
"elements",
"at",
"unique",
"keys",
"from",
"iterable",
"up",
"to",
"the",
"size",
"of",
"iterable",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L538-L553 | train |
doda/immutable-lodash | src/immutable-lodash.js | at | function at(map, paths) {
return paths.map((path) => {
return map.getIn(splitPath(path))
})
} | javascript | function at(map, paths) {
return paths.map((path) => {
return map.getIn(splitPath(path))
})
} | [
"function",
"at",
"(",
"map",
",",
"paths",
")",
"{",
"return",
"paths",
".",
"map",
"(",
"(",
"path",
")",
"=>",
"{",
"return",
"map",
".",
"getIn",
"(",
"splitPath",
"(",
"path",
")",
")",
"}",
")",
"}"
] | Creates an array of values corresponding to `paths` of `iterable`.
@static
@memberOf _
@category Iterable
@param {Iterable} iterable The iterable to iterate over.
@param {...(string|string[])} [paths] The property paths of elements to pick.
@returns {Iterable} Returns the picked values.
@example
let iterable = { 'a': [{ 'b': { 'c': 3 } }, 4] }
_.at(iterable, ['a[0].b.c', 'a[1]'])
// => [3, 4] | [
"Creates",
"an",
"array",
"of",
"values",
"corresponding",
"to",
"paths",
"of",
"iterable",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L596-L600 | train |
doda/immutable-lodash | src/immutable-lodash.js | defaults | function defaults(map, ...sources) {
return map.mergeWith((prev, next) => {
return prev === undefined ? next : prev
}, ...sources)
} | javascript | function defaults(map, ...sources) {
return map.mergeWith((prev, next) => {
return prev === undefined ? next : prev
}, ...sources)
} | [
"function",
"defaults",
"(",
"map",
",",
"...",
"sources",
")",
"{",
"return",
"map",
".",
"mergeWith",
"(",
"(",
"prev",
",",
"next",
")",
"=>",
"{",
"return",
"prev",
"===",
"undefined",
"?",
"next",
":",
"prev",
"}",
",",
"...",
"sources",
")",
"}"
] | Creates new iterable with all properties of source iterables that resolve
to `undefined`. Source iterables are applied from left to right.
Once a key is set, additional values of the same key are ignored.
@static
@memberOf _
@category Iterable
@param {Iterable} iterable The destination iterable.
@param {...Iterable} [sources] The source iterables.
@returns {Iterable} Returns `iterable`.
@see _.defaultsDeep
@example
_.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 })
// => { 'a': 1, 'b': 2 } | [
"Creates",
"new",
"iterable",
"with",
"all",
"properties",
"of",
"source",
"iterables",
"that",
"resolve",
"to",
"undefined",
".",
"Source",
"iterables",
"are",
"applied",
"from",
"left",
"to",
"right",
".",
"Once",
"a",
"key",
"is",
"set",
"additional",
"values",
"of",
"the",
"same",
"key",
"are",
"ignored",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L620-L624 | train |
doda/immutable-lodash | src/immutable-lodash.js | defaultsDeep | function defaultsDeep(map, ...sources) {
return map.mergeDeepWith((prev, next) => {
return prev === undefined ? next : prev
}, ...sources)
} | javascript | function defaultsDeep(map, ...sources) {
return map.mergeDeepWith((prev, next) => {
return prev === undefined ? next : prev
}, ...sources)
} | [
"function",
"defaultsDeep",
"(",
"map",
",",
"...",
"sources",
")",
"{",
"return",
"map",
".",
"mergeDeepWith",
"(",
"(",
"prev",
",",
"next",
")",
"=>",
"{",
"return",
"prev",
"===",
"undefined",
"?",
"next",
":",
"prev",
"}",
",",
"...",
"sources",
")",
"}"
] | This method is like `_.defaults` except that it recursively assigns
default properties.
@static
@memberOf _
@category Iterable
@param {Iterable} iterable The destination iterable.
@param {...Iterable} [sources] The source iterables.
@returns {Iterable} Returns `iterable`.
@see _.defaults
@example
_.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } })
// => { 'a': { 'b': 2, 'c': 3 } } | [
"This",
"method",
"is",
"like",
"_",
".",
"defaults",
"except",
"that",
"it",
"recursively",
"assigns",
"default",
"properties",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L643-L647 | train |
doda/immutable-lodash | src/immutable-lodash.js | pick | function pick(map, props) {
props = Set(props)
return _.pickBy(map, (key) => {
return props.has(key)
})
} | javascript | function pick(map, props) {
props = Set(props)
return _.pickBy(map, (key) => {
return props.has(key)
})
} | [
"function",
"pick",
"(",
"map",
",",
"props",
")",
"{",
"props",
"=",
"Set",
"(",
"props",
")",
"return",
"_",
".",
"pickBy",
"(",
"map",
",",
"(",
"key",
")",
"=>",
"{",
"return",
"props",
".",
"has",
"(",
"key",
")",
"}",
")",
"}"
] | Creates an iterable composed of the picked `iterable` properties.
@static
@memberOf _
@category Iterable
@param {Iterable} iterable The source iterable.
@param {...(string|string[])} [props] The property identifiers to pick.
@returns {Iterable} Returns the new iterable.
@example
let iterable = { 'a': 1, 'b': '2', 'c': 3 }
_.pick(iterable, ['a', 'c'])
// => { 'a': 1, 'c': 3 } | [
"Creates",
"an",
"iterable",
"composed",
"of",
"the",
"picked",
"iterable",
"properties",
"."
] | f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09 | https://github.com/doda/immutable-lodash/blob/f112a9b43cf2125be08b3bb41a7d2a6ef9c83f09/src/immutable-lodash.js#L743-L748 | train |
tadam313/sheet-db | src/util.js | coerceNumber | function coerceNumber(value) {
if (typeof value === 'number') {
return value;
}
let isfloat = /^\d*(\.|,)\d*$/;
if (isfloat.test(value)) {
value = value.replace(',', '.');
}
let numberValue = Number(value);
return numberValue == value || !value ? numberValue : value
} | javascript | function coerceNumber(value) {
if (typeof value === 'number') {
return value;
}
let isfloat = /^\d*(\.|,)\d*$/;
if (isfloat.test(value)) {
value = value.replace(',', '.');
}
let numberValue = Number(value);
return numberValue == value || !value ? numberValue : value
} | [
"function",
"coerceNumber",
"(",
"value",
")",
"{",
"if",
"(",
"typeof",
"value",
"===",
"'number'",
")",
"{",
"return",
"value",
";",
"}",
"let",
"isfloat",
"=",
"/",
"^\\d*(\\.|,)\\d*$",
"/",
";",
"if",
"(",
"isfloat",
".",
"test",
"(",
"value",
")",
")",
"{",
"value",
"=",
"value",
".",
"replace",
"(",
"','",
",",
"'.'",
")",
";",
"}",
"let",
"numberValue",
"=",
"Number",
"(",
"value",
")",
";",
"return",
"numberValue",
"==",
"value",
"||",
"!",
"value",
"?",
"numberValue",
":",
"value",
"}"
] | Tries to convert the value to number. Since we can not decide
the type of the data coming back from the spreadsheet, we try to coerce it to number.
Finally we check the coerced value whether is equals to the original value. This check assure that the coercion
won't break anything. Note the 'weak equality' operator here is really important.
@param {*} value
@returns {*} | [
"Tries",
"to",
"convert",
"the",
"value",
"to",
"number",
".",
"Since",
"we",
"can",
"not",
"decide",
"the",
"type",
"of",
"the",
"data",
"coming",
"back",
"from",
"the",
"spreadsheet",
"we",
"try",
"to",
"coerce",
"it",
"to",
"number",
".",
"Finally",
"we",
"check",
"the",
"coerced",
"value",
"whether",
"is",
"equals",
"to",
"the",
"original",
"value",
".",
"This",
"check",
"assure",
"that",
"the",
"coercion",
"won",
"t",
"break",
"anything",
".",
"Note",
"the",
"weak",
"equality",
"operator",
"here",
"is",
"really",
"important",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L25-L38 | train |
tadam313/sheet-db | src/util.js | coerceDate | function coerceDate(value) {
if (value instanceof Date) {
return value;
}
let timestamp = Date.parse(value);
if (!isNaN(timestamp)) {
return new Date(timestamp);
}
return value;
} | javascript | function coerceDate(value) {
if (value instanceof Date) {
return value;
}
let timestamp = Date.parse(value);
if (!isNaN(timestamp)) {
return new Date(timestamp);
}
return value;
} | [
"function",
"coerceDate",
"(",
"value",
")",
"{",
"if",
"(",
"value",
"instanceof",
"Date",
")",
"{",
"return",
"value",
";",
"}",
"let",
"timestamp",
"=",
"Date",
".",
"parse",
"(",
"value",
")",
";",
"if",
"(",
"!",
"isNaN",
"(",
"timestamp",
")",
")",
"{",
"return",
"new",
"Date",
"(",
"timestamp",
")",
";",
"}",
"return",
"value",
";",
"}"
] | Tries to convert the value to Date. First it try to parse it and if it gets a number,
the Date constructor will be fed with that.
@param {*} value
@returns {*} | [
"Tries",
"to",
"convert",
"the",
"value",
"to",
"Date",
".",
"First",
"it",
"try",
"to",
"parse",
"it",
"and",
"if",
"it",
"gets",
"a",
"number",
"the",
"Date",
"constructor",
"will",
"be",
"fed",
"with",
"that",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L47-L59 | train |
tadam313/sheet-db | src/util.js | coerceValue | function coerceValue(value) {
let numValue = coerceNumber(value);
if (numValue === value) {
return coerceDate(value);
}
return numValue;
} | javascript | function coerceValue(value) {
let numValue = coerceNumber(value);
if (numValue === value) {
return coerceDate(value);
}
return numValue;
} | [
"function",
"coerceValue",
"(",
"value",
")",
"{",
"let",
"numValue",
"=",
"coerceNumber",
"(",
"value",
")",
";",
"if",
"(",
"numValue",
"===",
"value",
")",
"{",
"return",
"coerceDate",
"(",
"value",
")",
";",
"}",
"return",
"numValue",
";",
"}"
] | We can not decide the type of the data coming back from the spreadsheet,
we try to coerce it to Date or Number. If both "failes" it will leave the value unchanged.
@param {*} value
@returns {*} | [
"We",
"can",
"not",
"decide",
"the",
"type",
"of",
"the",
"data",
"coming",
"back",
"from",
"the",
"spreadsheet",
"we",
"try",
"to",
"coerce",
"it",
"to",
"Date",
"or",
"Number",
".",
"If",
"both",
"failes",
"it",
"will",
"leave",
"the",
"value",
"unchanged",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L68-L77 | train |
tadam313/sheet-db | src/util.js | getArrayFields | function getArrayFields(array) {
return (array || []).reduce((old, current) => {
arrayDiff(Object.keys(current), old)
.forEach(key => old.push(key));
return old;
}, []);
} | javascript | function getArrayFields(array) {
return (array || []).reduce((old, current) => {
arrayDiff(Object.keys(current), old)
.forEach(key => old.push(key));
return old;
}, []);
} | [
"function",
"getArrayFields",
"(",
"array",
")",
"{",
"return",
"(",
"array",
"||",
"[",
"]",
")",
".",
"reduce",
"(",
"(",
"old",
",",
"current",
")",
"=>",
"{",
"arrayDiff",
"(",
"Object",
".",
"keys",
"(",
"current",
")",
",",
"old",
")",
".",
"forEach",
"(",
"key",
"=>",
"old",
".",
"push",
"(",
"key",
")",
")",
";",
"return",
"old",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] | Retrieves every field in the array of objects. These are collected in a Hash-map which means they are unique.
@param {array} array Subject of the operation
@returns {array} | [
"Retrieves",
"every",
"field",
"in",
"the",
"array",
"of",
"objects",
".",
"These",
"are",
"collected",
"in",
"a",
"Hash",
"-",
"map",
"which",
"means",
"they",
"are",
"unique",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L85-L92 | train |
tadam313/sheet-db | src/util.js | arrayDiff | function arrayDiff(arrayTarget, arrayCheck) {
if (!(arrayTarget instanceof Array) || !(arrayCheck instanceof Array)) {
throw new Error('Both objects have to be an array');
}
return arrayTarget.filter(item => !~arrayCheck.indexOf(item));
} | javascript | function arrayDiff(arrayTarget, arrayCheck) {
if (!(arrayTarget instanceof Array) || !(arrayCheck instanceof Array)) {
throw new Error('Both objects have to be an array');
}
return arrayTarget.filter(item => !~arrayCheck.indexOf(item));
} | [
"function",
"arrayDiff",
"(",
"arrayTarget",
",",
"arrayCheck",
")",
"{",
"if",
"(",
"!",
"(",
"arrayTarget",
"instanceof",
"Array",
")",
"||",
"!",
"(",
"arrayCheck",
"instanceof",
"Array",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Both objects have to be an array'",
")",
";",
"}",
"return",
"arrayTarget",
".",
"filter",
"(",
"item",
"=>",
"!",
"~",
"arrayCheck",
".",
"indexOf",
"(",
"item",
")",
")",
";",
"}"
] | Determines which elements from arrayTarget are not present in arrayCheck.
@param {array} arrayTarget Target of the check
@param {array} arrayCheck Subject of the check
@returns {array} | [
"Determines",
"which",
"elements",
"from",
"arrayTarget",
"are",
"not",
"present",
"in",
"arrayCheck",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L101-L107 | train |
tadam313/sheet-db | src/util.js | copyMetaProperties | function copyMetaProperties(dest, source) {
if (!dest || !source) {
return dest;
}
let fields = ['_id', '_updated'];
for (let field of fields) {
dest[field] = source[field];
}
return dest;
} | javascript | function copyMetaProperties(dest, source) {
if (!dest || !source) {
return dest;
}
let fields = ['_id', '_updated'];
for (let field of fields) {
dest[field] = source[field];
}
return dest;
} | [
"function",
"copyMetaProperties",
"(",
"dest",
",",
"source",
")",
"{",
"if",
"(",
"!",
"dest",
"||",
"!",
"source",
")",
"{",
"return",
"dest",
";",
"}",
"let",
"fields",
"=",
"[",
"'_id'",
",",
"'_updated'",
"]",
";",
"for",
"(",
"let",
"field",
"of",
"fields",
")",
"{",
"dest",
"[",
"field",
"]",
"=",
"source",
"[",
"field",
"]",
";",
"}",
"return",
"dest",
";",
"}"
] | Grab meta google drive meta properties from source and add those to dest.
@param dest
@param source | [
"Grab",
"meta",
"google",
"drive",
"meta",
"properties",
"from",
"source",
"and",
"add",
"those",
"to",
"dest",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/util.js#L124-L136 | train |
GitbookIO/plugin-styles-sass | index.js | renderSASS | function renderSASS(input, output) {
var d = Q.defer();
sass.render({
file: input
}, function (e, out) {
if (e) return d.reject(e);
fs.writeFileSync(output, out.css);
d.resolve();
});
return d.promise;
} | javascript | function renderSASS(input, output) {
var d = Q.defer();
sass.render({
file: input
}, function (e, out) {
if (e) return d.reject(e);
fs.writeFileSync(output, out.css);
d.resolve();
});
return d.promise;
} | [
"function",
"renderSASS",
"(",
"input",
",",
"output",
")",
"{",
"var",
"d",
"=",
"Q",
".",
"defer",
"(",
")",
";",
"sass",
".",
"render",
"(",
"{",
"file",
":",
"input",
"}",
",",
"function",
"(",
"e",
",",
"out",
")",
"{",
"if",
"(",
"e",
")",
"return",
"d",
".",
"reject",
"(",
"e",
")",
";",
"fs",
".",
"writeFileSync",
"(",
"output",
",",
"out",
".",
"css",
")",
";",
"d",
".",
"resolve",
"(",
")",
";",
"}",
")",
";",
"return",
"d",
".",
"promise",
";",
"}"
] | Compile a SASS file into a css | [
"Compile",
"a",
"SASS",
"file",
"into",
"a",
"css"
] | d073d9db46e6c669992b9ed98dc1a48f1483e6ce | https://github.com/GitbookIO/plugin-styles-sass/blob/d073d9db46e6c669992b9ed98dc1a48f1483e6ce/index.js#L8-L21 | train |
GitbookIO/plugin-styles-sass | index.js | function() {
var book = this;
var styles = book.config.get('styles');
return _.reduce(styles, function(prev, filename, type) {
return prev.then(function() {
var extension = path.extname(filename).toLowerCase();
if (extension != '.sass' && extension != '.scss') return;
book.log.info.ln('compile sass file: ', filename);
// Temporary CSS file
var tmpfile = type+'-'+Date.now()+'.css';
// Replace config
book.config.set('styles.'+type, tmpfile);
return renderSASS(
book.resolve(filename),
path.resolve(book.options.output, tmpfile)
);
});
}, Q());
} | javascript | function() {
var book = this;
var styles = book.config.get('styles');
return _.reduce(styles, function(prev, filename, type) {
return prev.then(function() {
var extension = path.extname(filename).toLowerCase();
if (extension != '.sass' && extension != '.scss') return;
book.log.info.ln('compile sass file: ', filename);
// Temporary CSS file
var tmpfile = type+'-'+Date.now()+'.css';
// Replace config
book.config.set('styles.'+type, tmpfile);
return renderSASS(
book.resolve(filename),
path.resolve(book.options.output, tmpfile)
);
});
}, Q());
} | [
"function",
"(",
")",
"{",
"var",
"book",
"=",
"this",
";",
"var",
"styles",
"=",
"book",
".",
"config",
".",
"get",
"(",
"'styles'",
")",
";",
"return",
"_",
".",
"reduce",
"(",
"styles",
",",
"function",
"(",
"prev",
",",
"filename",
",",
"type",
")",
"{",
"return",
"prev",
".",
"then",
"(",
"function",
"(",
")",
"{",
"var",
"extension",
"=",
"path",
".",
"extname",
"(",
"filename",
")",
".",
"toLowerCase",
"(",
")",
";",
"if",
"(",
"extension",
"!=",
"'.sass'",
"&&",
"extension",
"!=",
"'.scss'",
")",
"return",
";",
"book",
".",
"log",
".",
"info",
".",
"ln",
"(",
"'compile sass file: '",
",",
"filename",
")",
";",
"var",
"tmpfile",
"=",
"type",
"+",
"'-'",
"+",
"Date",
".",
"now",
"(",
")",
"+",
"'.css'",
";",
"book",
".",
"config",
".",
"set",
"(",
"'styles.'",
"+",
"type",
",",
"tmpfile",
")",
";",
"return",
"renderSASS",
"(",
"book",
".",
"resolve",
"(",
"filename",
")",
",",
"path",
".",
"resolve",
"(",
"book",
".",
"options",
".",
"output",
",",
"tmpfile",
")",
")",
";",
"}",
")",
";",
"}",
",",
"Q",
"(",
")",
")",
";",
"}"
] | Compile sass as CSS | [
"Compile",
"sass",
"as",
"CSS"
] | d073d9db46e6c669992b9ed98dc1a48f1483e6ce | https://github.com/GitbookIO/plugin-styles-sass/blob/d073d9db46e6c669992b9ed98dc1a48f1483e6ce/index.js#L26-L50 | train |
|
switer/muxjs | lib/keypath.js | _keyPathNormalize | function _keyPathNormalize(kp) {
return new String(kp).replace(/\[([^\[\]]+)\]/g, function(m, k) {
return '.' + k.replace(/^["']|["']$/g, '')
})
} | javascript | function _keyPathNormalize(kp) {
return new String(kp).replace(/\[([^\[\]]+)\]/g, function(m, k) {
return '.' + k.replace(/^["']|["']$/g, '')
})
} | [
"function",
"_keyPathNormalize",
"(",
"kp",
")",
"{",
"return",
"new",
"String",
"(",
"kp",
")",
".",
"replace",
"(",
"/",
"\\[([^\\[\\]]+)\\]",
"/",
"g",
",",
"function",
"(",
"m",
",",
"k",
")",
"{",
"return",
"'.'",
"+",
"k",
".",
"replace",
"(",
"/",
"^[\"']|[\"']$",
"/",
"g",
",",
"''",
")",
"}",
")",
"}"
] | normalize all access ways into dot access
@example "person.books[1].title" --> "person.books.1.title" | [
"normalize",
"all",
"access",
"ways",
"into",
"dot",
"access"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/keypath.js#L7-L11 | train |
switer/muxjs | lib/keypath.js | _set | function _set(obj, keypath, value, hook) {
var parts = _keyPathNormalize(keypath).split('.')
var last = parts.pop()
var dest = obj
parts.forEach(function(key) {
// Still set to non-object, just throw that error
dest = dest[key]
})
if (hook) {
// hook proxy set value
hook(dest, last, value)
} else {
dest[last] = value
}
return obj
} | javascript | function _set(obj, keypath, value, hook) {
var parts = _keyPathNormalize(keypath).split('.')
var last = parts.pop()
var dest = obj
parts.forEach(function(key) {
// Still set to non-object, just throw that error
dest = dest[key]
})
if (hook) {
// hook proxy set value
hook(dest, last, value)
} else {
dest[last] = value
}
return obj
} | [
"function",
"_set",
"(",
"obj",
",",
"keypath",
",",
"value",
",",
"hook",
")",
"{",
"var",
"parts",
"=",
"_keyPathNormalize",
"(",
"keypath",
")",
".",
"split",
"(",
"'.'",
")",
"var",
"last",
"=",
"parts",
".",
"pop",
"(",
")",
"var",
"dest",
"=",
"obj",
"parts",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"dest",
"=",
"dest",
"[",
"key",
"]",
"}",
")",
"if",
"(",
"hook",
")",
"{",
"hook",
"(",
"dest",
",",
"last",
",",
"value",
")",
"}",
"else",
"{",
"dest",
"[",
"last",
"]",
"=",
"value",
"}",
"return",
"obj",
"}"
] | set value to object by keypath | [
"set",
"value",
"to",
"object",
"by",
"keypath"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/keypath.js#L15-L30 | train |
switer/muxjs | lib/keypath.js | _get | function _get(obj, keypath) {
var parts = _keyPathNormalize(keypath).split('.')
var dest = obj
parts.forEach(function(key) {
if (isNon(dest)) return !(dest = undf())
dest = dest[key]
})
return dest
} | javascript | function _get(obj, keypath) {
var parts = _keyPathNormalize(keypath).split('.')
var dest = obj
parts.forEach(function(key) {
if (isNon(dest)) return !(dest = undf())
dest = dest[key]
})
return dest
} | [
"function",
"_get",
"(",
"obj",
",",
"keypath",
")",
"{",
"var",
"parts",
"=",
"_keyPathNormalize",
"(",
"keypath",
")",
".",
"split",
"(",
"'.'",
")",
"var",
"dest",
"=",
"obj",
"parts",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"if",
"(",
"isNon",
"(",
"dest",
")",
")",
"return",
"!",
"(",
"dest",
"=",
"undf",
"(",
")",
")",
"dest",
"=",
"dest",
"[",
"key",
"]",
"}",
")",
"return",
"dest",
"}"
] | get value of object by keypath | [
"get",
"value",
"of",
"object",
"by",
"keypath"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/keypath.js#L43-L51 | train |
switer/muxjs | lib/keypath.js | _join | function _join(pre, tail) {
var _hasBegin = !!pre
if(!_hasBegin) pre = ''
if (/^\[.*\]$/.exec(tail)) return pre + tail
else if (typeof(tail) == 'number') return pre + '[' + tail + ']'
else if (_hasBegin) return pre + '.' + tail
else return tail
} | javascript | function _join(pre, tail) {
var _hasBegin = !!pre
if(!_hasBegin) pre = ''
if (/^\[.*\]$/.exec(tail)) return pre + tail
else if (typeof(tail) == 'number') return pre + '[' + tail + ']'
else if (_hasBegin) return pre + '.' + tail
else return tail
} | [
"function",
"_join",
"(",
"pre",
",",
"tail",
")",
"{",
"var",
"_hasBegin",
"=",
"!",
"!",
"pre",
"if",
"(",
"!",
"_hasBegin",
")",
"pre",
"=",
"''",
"if",
"(",
"/",
"^\\[.*\\]$",
"/",
".",
"exec",
"(",
"tail",
")",
")",
"return",
"pre",
"+",
"tail",
"else",
"if",
"(",
"typeof",
"(",
"tail",
")",
"==",
"'number'",
")",
"return",
"pre",
"+",
"'['",
"+",
"tail",
"+",
"']'",
"else",
"if",
"(",
"_hasBegin",
")",
"return",
"pre",
"+",
"'.'",
"+",
"tail",
"else",
"return",
"tail",
"}"
] | append path to a base path | [
"append",
"path",
"to",
"a",
"base",
"path"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/keypath.js#L56-L63 | train |
chip-js/fragments-js | src/util/toFragment.js | listToFragment | function listToFragment(list) {
var fragment = document.createDocumentFragment();
for (var i = 0, l = list.length; i < l; i++) {
// Use toFragment since this may be an array of text, a jQuery object of `<template>`s, etc.
fragment.appendChild(toFragment(list[i]));
if (l === list.length + 1) {
// adjust for NodeLists which are live, they shrink as we pull nodes out of the DOM
i--;
l--;
}
}
return fragment;
} | javascript | function listToFragment(list) {
var fragment = document.createDocumentFragment();
for (var i = 0, l = list.length; i < l; i++) {
// Use toFragment since this may be an array of text, a jQuery object of `<template>`s, etc.
fragment.appendChild(toFragment(list[i]));
if (l === list.length + 1) {
// adjust for NodeLists which are live, they shrink as we pull nodes out of the DOM
i--;
l--;
}
}
return fragment;
} | [
"function",
"listToFragment",
"(",
"list",
")",
"{",
"var",
"fragment",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
";",
"for",
"(",
"var",
"i",
"=",
"0",
",",
"l",
"=",
"list",
".",
"length",
";",
"i",
"<",
"l",
";",
"i",
"++",
")",
"{",
"fragment",
".",
"appendChild",
"(",
"toFragment",
"(",
"list",
"[",
"i",
"]",
")",
")",
";",
"if",
"(",
"l",
"===",
"list",
".",
"length",
"+",
"1",
")",
"{",
"i",
"--",
";",
"l",
"--",
";",
"}",
"}",
"return",
"fragment",
";",
"}"
] | Converts an HTMLCollection, NodeList, jQuery object, or array into a document fragment. | [
"Converts",
"an",
"HTMLCollection",
"NodeList",
"jQuery",
"object",
"or",
"array",
"into",
"a",
"document",
"fragment",
"."
] | 5d613ea42c3823423efb01fce4ffef80c7f5ce0f | https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/util/toFragment.js#L50-L62 | train |
chip-js/fragments-js | src/util/toFragment.js | function(string) {
if (!string) {
var fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode(''));
return fragment;
}
var templateElement;
templateElement = document.createElement('template');
templateElement.innerHTML = string;
return templateElement.content;
} | javascript | function(string) {
if (!string) {
var fragment = document.createDocumentFragment();
fragment.appendChild(document.createTextNode(''));
return fragment;
}
var templateElement;
templateElement = document.createElement('template');
templateElement.innerHTML = string;
return templateElement.content;
} | [
"function",
"(",
"string",
")",
"{",
"if",
"(",
"!",
"string",
")",
"{",
"var",
"fragment",
"=",
"document",
".",
"createDocumentFragment",
"(",
")",
";",
"fragment",
".",
"appendChild",
"(",
"document",
".",
"createTextNode",
"(",
"''",
")",
")",
";",
"return",
"fragment",
";",
"}",
"var",
"templateElement",
";",
"templateElement",
"=",
"document",
".",
"createElement",
"(",
"'template'",
")",
";",
"templateElement",
".",
"innerHTML",
"=",
"string",
";",
"return",
"templateElement",
".",
"content",
";",
"}"
] | Converts a string of HTML text into a document fragment. | [
"Converts",
"a",
"string",
"of",
"HTML",
"text",
"into",
"a",
"document",
"fragment",
"."
] | 5d613ea42c3823423efb01fce4ffef80c7f5ce0f | https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/util/toFragment.js#L65-L75 | train |
|
nahody/postcss-export-vars | index.js | createFile | function createFile() {
let fileContent = '';
/*
* Customize data by type
*/
switch (options.type) {
case 'js':
fileContent += `'use strict';` + '\n';
for (let collectionKey in _variableCollection) {
fileContent += `const ${collectionKey} = '${_variableCollection[collectionKey]}';` + '\n';
}
if (_.endsWith(options.file, 'js') === false) options.file += '.js';
break;
default:
/* json */
fileContent = JSON.stringify(_variableCollection);
if (_.endsWith(options.file, 'json') === false) options.file += '.json';
}
/*
* Write file
*/
return fs.writeFileSync(options.file, fileContent, 'utf8');
} | javascript | function createFile() {
let fileContent = '';
/*
* Customize data by type
*/
switch (options.type) {
case 'js':
fileContent += `'use strict';` + '\n';
for (let collectionKey in _variableCollection) {
fileContent += `const ${collectionKey} = '${_variableCollection[collectionKey]}';` + '\n';
}
if (_.endsWith(options.file, 'js') === false) options.file += '.js';
break;
default:
/* json */
fileContent = JSON.stringify(_variableCollection);
if (_.endsWith(options.file, 'json') === false) options.file += '.json';
}
/*
* Write file
*/
return fs.writeFileSync(options.file, fileContent, 'utf8');
} | [
"function",
"createFile",
"(",
")",
"{",
"let",
"fileContent",
"=",
"''",
";",
"switch",
"(",
"options",
".",
"type",
")",
"{",
"case",
"'js'",
":",
"fileContent",
"+=",
"`",
"`",
"+",
"'\\n'",
";",
"\\n",
"for",
"(",
"let",
"collectionKey",
"in",
"_variableCollection",
")",
"{",
"fileContent",
"+=",
"`",
"${",
"collectionKey",
"}",
"${",
"_variableCollection",
"[",
"collectionKey",
"]",
"}",
"`",
"+",
"'\\n'",
";",
"}",
"\\n",
"if",
"(",
"_",
".",
"endsWith",
"(",
"options",
".",
"file",
",",
"'js'",
")",
"===",
"false",
")",
"options",
".",
"file",
"+=",
"'.js'",
";",
"}",
"break",
";",
"}"
] | Create file. | [
"Create",
"file",
"."
] | ee6afbe1c6ec5091912e636b42a661a25e447d7d | https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L29-L56 | train |
nahody/postcss-export-vars | index.js | propertyMatch | function propertyMatch(property) {
for (let count = 0; count < options.match.length; count++) {
if (property.indexOf(options.match[count]) > -1) {
return true;
}
}
return false;
} | javascript | function propertyMatch(property) {
for (let count = 0; count < options.match.length; count++) {
if (property.indexOf(options.match[count]) > -1) {
return true;
}
}
return false;
} | [
"function",
"propertyMatch",
"(",
"property",
")",
"{",
"for",
"(",
"let",
"count",
"=",
"0",
";",
"count",
"<",
"options",
".",
"match",
".",
"length",
";",
"count",
"++",
")",
"{",
"if",
"(",
"property",
".",
"indexOf",
"(",
"options",
".",
"match",
"[",
"count",
"]",
")",
">",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Detect if property fulfill one matching value.
@param property
@returns {boolean} | [
"Detect",
"if",
"property",
"fulfill",
"one",
"matching",
"value",
"."
] | ee6afbe1c6ec5091912e636b42a661a25e447d7d | https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L64-L72 | train |
nahody/postcss-export-vars | index.js | extractVariables | function extractVariables(value) {
let regex = [/var\((.*?)\)/g, /\$([a-zA-Z0-9_\-]*)/g ],
result = [],
matchResult;
regex.forEach(expression => {
while (matchResult = expression.exec(value)) {
result.push({ origin: matchResult[0], variable: matchResult[1] });
}
});
return result;
} | javascript | function extractVariables(value) {
let regex = [/var\((.*?)\)/g, /\$([a-zA-Z0-9_\-]*)/g ],
result = [],
matchResult;
regex.forEach(expression => {
while (matchResult = expression.exec(value)) {
result.push({ origin: matchResult[0], variable: matchResult[1] });
}
});
return result;
} | [
"function",
"extractVariables",
"(",
"value",
")",
"{",
"let",
"regex",
"=",
"[",
"/",
"var\\((.*?)\\)",
"/",
"g",
",",
"/",
"\\$([a-zA-Z0-9_\\-]*)",
"/",
"g",
"]",
",",
"result",
"=",
"[",
"]",
",",
"matchResult",
";",
"regex",
".",
"forEach",
"(",
"expression",
"=>",
"{",
"while",
"(",
"matchResult",
"=",
"expression",
".",
"exec",
"(",
"value",
")",
")",
"{",
"result",
".",
"push",
"(",
"{",
"origin",
":",
"matchResult",
"[",
"0",
"]",
",",
"variable",
":",
"matchResult",
"[",
"1",
"]",
"}",
")",
";",
"}",
"}",
")",
";",
"return",
"result",
";",
"}"
] | Extract custom properties and sass like variables from value.
Return each found variable as array with objects.
@example 'test vars(--var1) + $width'
result in array with objects:
[{origin:'vars(--var1)', variable: '--var1'},{origin:'$width', variable: 'width'}]
@param value
@returns {Array} | [
"Extract",
"custom",
"properties",
"and",
"sass",
"like",
"variables",
"from",
"value",
".",
"Return",
"each",
"found",
"variable",
"as",
"array",
"with",
"objects",
"."
] | ee6afbe1c6ec5091912e636b42a661a25e447d7d | https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L84-L96 | train |
nahody/postcss-export-vars | index.js | resolveReferences | function resolveReferences() {
for (let key in _variableCollection) {
let referenceVariables = extractVariables(_variableCollection[key]);
for (let current = 0; current < referenceVariables.length; current++) {
if (_.isEmpty(_variableCollection[_.camelCase(referenceVariables[current].variable)]) === false) {
_variableCollection[key] = _variableCollection[key].replace(referenceVariables[current].origin, _variableCollection[_.camelCase(referenceVariables[current].variable)]);
}
}
}
} | javascript | function resolveReferences() {
for (let key in _variableCollection) {
let referenceVariables = extractVariables(_variableCollection[key]);
for (let current = 0; current < referenceVariables.length; current++) {
if (_.isEmpty(_variableCollection[_.camelCase(referenceVariables[current].variable)]) === false) {
_variableCollection[key] = _variableCollection[key].replace(referenceVariables[current].origin, _variableCollection[_.camelCase(referenceVariables[current].variable)]);
}
}
}
} | [
"function",
"resolveReferences",
"(",
")",
"{",
"for",
"(",
"let",
"key",
"in",
"_variableCollection",
")",
"{",
"let",
"referenceVariables",
"=",
"extractVariables",
"(",
"_variableCollection",
"[",
"key",
"]",
")",
";",
"for",
"(",
"let",
"current",
"=",
"0",
";",
"current",
"<",
"referenceVariables",
".",
"length",
";",
"current",
"++",
")",
"{",
"if",
"(",
"_",
".",
"isEmpty",
"(",
"_variableCollection",
"[",
"_",
".",
"camelCase",
"(",
"referenceVariables",
"[",
"current",
"]",
".",
"variable",
")",
"]",
")",
"===",
"false",
")",
"{",
"_variableCollection",
"[",
"key",
"]",
"=",
"_variableCollection",
"[",
"key",
"]",
".",
"replace",
"(",
"referenceVariables",
"[",
"current",
"]",
".",
"origin",
",",
"_variableCollection",
"[",
"_",
".",
"camelCase",
"(",
"referenceVariables",
"[",
"current",
"]",
".",
"variable",
")",
"]",
")",
";",
"}",
"}",
"}",
"}"
] | Resolve references on variable values to other variables. | [
"Resolve",
"references",
"on",
"variable",
"values",
"to",
"other",
"variables",
"."
] | ee6afbe1c6ec5091912e636b42a661a25e447d7d | https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L101-L113 | train |
nahody/postcss-export-vars | index.js | escapeValue | function escapeValue(value) {
switch (options.type) {
case 'js':
return value.replace(/'/g, '\\\'');
case 'json':
return value.replace(/"/g, '\\"');
default:
return value;
}
} | javascript | function escapeValue(value) {
switch (options.type) {
case 'js':
return value.replace(/'/g, '\\\'');
case 'json':
return value.replace(/"/g, '\\"');
default:
return value;
}
} | [
"function",
"escapeValue",
"(",
"value",
")",
"{",
"switch",
"(",
"options",
".",
"type",
")",
"{",
"case",
"'js'",
":",
"return",
"value",
".",
"replace",
"(",
"/",
"'",
"/",
"g",
",",
"'\\\\\\''",
")",
";",
"\\\\",
"\\'",
"}",
"}"
] | Escape values depends on type.
For JS escape single quote, for json double quotes.
For everything else return origin value.
@param value {string}
@returns {string} | [
"Escape",
"values",
"depends",
"on",
"type",
"."
] | ee6afbe1c6ec5091912e636b42a661a25e447d7d | https://github.com/nahody/postcss-export-vars/blob/ee6afbe1c6ec5091912e636b42a661a25e447d7d/index.js#L124-L133 | train |
kadamwhite/tokenize-markdown | tokenize-markdown.js | convertToTokens | function convertToTokens( contents, filterParams ) {
var tokens = marked.lexer( contents );
// Simple case: no filtering needs to happen
if ( ! filterParams ) {
// Return the array of tokens from this content
return tokens;
}
/**
* Filter method to check whether a token is valid, based on the provided
* object of filter parameters
*
* If the filter object defines a RegExp for a key, test the token's property
* against that RegExp; otherwise, do a strict equality check between the
* provided value and the token's value for a given key.
*
* @param {Object} token A token object
* @return {Boolean} Whether the provided token object is valid
*/
function isTokenValid( token ) {
/**
* Reducer function to check token validity: start the token out as valid,
* then reduce through the provided filter parameters, updating the validity
* of the token after checking each value.
*
* @param {Boolean} valid Reducer function memo value
* @param {String|RegExp} targetValue The expected value of the specified property
* on this token, or else a RegExp against which
* to test that property
* @param {String} key The key within the token to test
* @return {Boolean} Whether the token is still valid, after
* validating the provided key
*/
function checkTokenParam( valid, targetValue, key ) {
// Once invalid, always invalid: fast-fail in this case
if ( ! valid ) {
return false;
}
// Without a target value, filtering doesn't mean much: move along
if ( typeof targetValue === 'undefined' ) {
return true;
}
var tokenPropToTest = token[ key ];
if ( isRegExp( targetValue ) ) {
// Special-case if the target value is a RegExp
return targetValue.test( tokenPropToTest );
}
return tokenPropToTest === targetValue;
}
// Check each property on this token against the provided params
return reduce( filterParams, checkTokenParam, true );
}
// Return a filtered array of tokens from the provided content
return tokens.filter( isTokenValid );
} | javascript | function convertToTokens( contents, filterParams ) {
var tokens = marked.lexer( contents );
// Simple case: no filtering needs to happen
if ( ! filterParams ) {
// Return the array of tokens from this content
return tokens;
}
/**
* Filter method to check whether a token is valid, based on the provided
* object of filter parameters
*
* If the filter object defines a RegExp for a key, test the token's property
* against that RegExp; otherwise, do a strict equality check between the
* provided value and the token's value for a given key.
*
* @param {Object} token A token object
* @return {Boolean} Whether the provided token object is valid
*/
function isTokenValid( token ) {
/**
* Reducer function to check token validity: start the token out as valid,
* then reduce through the provided filter parameters, updating the validity
* of the token after checking each value.
*
* @param {Boolean} valid Reducer function memo value
* @param {String|RegExp} targetValue The expected value of the specified property
* on this token, or else a RegExp against which
* to test that property
* @param {String} key The key within the token to test
* @return {Boolean} Whether the token is still valid, after
* validating the provided key
*/
function checkTokenParam( valid, targetValue, key ) {
// Once invalid, always invalid: fast-fail in this case
if ( ! valid ) {
return false;
}
// Without a target value, filtering doesn't mean much: move along
if ( typeof targetValue === 'undefined' ) {
return true;
}
var tokenPropToTest = token[ key ];
if ( isRegExp( targetValue ) ) {
// Special-case if the target value is a RegExp
return targetValue.test( tokenPropToTest );
}
return tokenPropToTest === targetValue;
}
// Check each property on this token against the provided params
return reduce( filterParams, checkTokenParam, true );
}
// Return a filtered array of tokens from the provided content
return tokens.filter( isTokenValid );
} | [
"function",
"convertToTokens",
"(",
"contents",
",",
"filterParams",
")",
"{",
"var",
"tokens",
"=",
"marked",
".",
"lexer",
"(",
"contents",
")",
";",
"if",
"(",
"!",
"filterParams",
")",
"{",
"return",
"tokens",
";",
"}",
"function",
"isTokenValid",
"(",
"token",
")",
"{",
"function",
"checkTokenParam",
"(",
"valid",
",",
"targetValue",
",",
"key",
")",
"{",
"if",
"(",
"!",
"valid",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"typeof",
"targetValue",
"===",
"'undefined'",
")",
"{",
"return",
"true",
";",
"}",
"var",
"tokenPropToTest",
"=",
"token",
"[",
"key",
"]",
";",
"if",
"(",
"isRegExp",
"(",
"targetValue",
")",
")",
"{",
"return",
"targetValue",
".",
"test",
"(",
"tokenPropToTest",
")",
";",
"}",
"return",
"tokenPropToTest",
"===",
"targetValue",
";",
"}",
"return",
"reduce",
"(",
"filterParams",
",",
"checkTokenParam",
",",
"true",
")",
";",
"}",
"return",
"tokens",
".",
"filter",
"(",
"isTokenValid",
")",
";",
"}"
] | Convert provided content into a token list with marked
@param {String} contents A markdown string or file's contents
@param {Object} [filterParams] An optional array of properties to use to
filter the returned tokens for this file
@return {Object} | [
"Convert",
"provided",
"content",
"into",
"a",
"token",
"list",
"with",
"marked"
] | ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0 | https://github.com/kadamwhite/tokenize-markdown/blob/ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0/tokenize-markdown.js#L16-L77 | train |
kadamwhite/tokenize-markdown | tokenize-markdown.js | isTokenValid | function isTokenValid( token ) {
/**
* Reducer function to check token validity: start the token out as valid,
* then reduce through the provided filter parameters, updating the validity
* of the token after checking each value.
*
* @param {Boolean} valid Reducer function memo value
* @param {String|RegExp} targetValue The expected value of the specified property
* on this token, or else a RegExp against which
* to test that property
* @param {String} key The key within the token to test
* @return {Boolean} Whether the token is still valid, after
* validating the provided key
*/
function checkTokenParam( valid, targetValue, key ) {
// Once invalid, always invalid: fast-fail in this case
if ( ! valid ) {
return false;
}
// Without a target value, filtering doesn't mean much: move along
if ( typeof targetValue === 'undefined' ) {
return true;
}
var tokenPropToTest = token[ key ];
if ( isRegExp( targetValue ) ) {
// Special-case if the target value is a RegExp
return targetValue.test( tokenPropToTest );
}
return tokenPropToTest === targetValue;
}
// Check each property on this token against the provided params
return reduce( filterParams, checkTokenParam, true );
} | javascript | function isTokenValid( token ) {
/**
* Reducer function to check token validity: start the token out as valid,
* then reduce through the provided filter parameters, updating the validity
* of the token after checking each value.
*
* @param {Boolean} valid Reducer function memo value
* @param {String|RegExp} targetValue The expected value of the specified property
* on this token, or else a RegExp against which
* to test that property
* @param {String} key The key within the token to test
* @return {Boolean} Whether the token is still valid, after
* validating the provided key
*/
function checkTokenParam( valid, targetValue, key ) {
// Once invalid, always invalid: fast-fail in this case
if ( ! valid ) {
return false;
}
// Without a target value, filtering doesn't mean much: move along
if ( typeof targetValue === 'undefined' ) {
return true;
}
var tokenPropToTest = token[ key ];
if ( isRegExp( targetValue ) ) {
// Special-case if the target value is a RegExp
return targetValue.test( tokenPropToTest );
}
return tokenPropToTest === targetValue;
}
// Check each property on this token against the provided params
return reduce( filterParams, checkTokenParam, true );
} | [
"function",
"isTokenValid",
"(",
"token",
")",
"{",
"function",
"checkTokenParam",
"(",
"valid",
",",
"targetValue",
",",
"key",
")",
"{",
"if",
"(",
"!",
"valid",
")",
"{",
"return",
"false",
";",
"}",
"if",
"(",
"typeof",
"targetValue",
"===",
"'undefined'",
")",
"{",
"return",
"true",
";",
"}",
"var",
"tokenPropToTest",
"=",
"token",
"[",
"key",
"]",
";",
"if",
"(",
"isRegExp",
"(",
"targetValue",
")",
")",
"{",
"return",
"targetValue",
".",
"test",
"(",
"tokenPropToTest",
")",
";",
"}",
"return",
"tokenPropToTest",
"===",
"targetValue",
";",
"}",
"return",
"reduce",
"(",
"filterParams",
",",
"checkTokenParam",
",",
"true",
")",
";",
"}"
] | Filter method to check whether a token is valid, based on the provided
object of filter parameters
If the filter object defines a RegExp for a key, test the token's property
against that RegExp; otherwise, do a strict equality check between the
provided value and the token's value for a given key.
@param {Object} token A token object
@return {Boolean} Whether the provided token object is valid | [
"Filter",
"method",
"to",
"check",
"whether",
"a",
"token",
"is",
"valid",
"based",
"on",
"the",
"provided",
"object",
"of",
"filter",
"parameters"
] | ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0 | https://github.com/kadamwhite/tokenize-markdown/blob/ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0/tokenize-markdown.js#L36-L73 | train |
kadamwhite/tokenize-markdown | tokenize-markdown.js | tokenizeMarkdownFromFiles | function tokenizeMarkdownFromFiles( files, filterParams ) {
/**
* Read in the provided file and return its contents as markdown tokens
*
* @param {String} file A file path to read in
* @return {Array} An array of the individual markdown tokens found
* within the provided list of files
*/
function readAndTokenize( file ) {
// Read the file
var fileContents = grunt.file.read( file );
// Map file into an object defining the tokens for this file
return {
file: file,
tokens: convertToTokens( fileContents, filterParams )
};
}
// Expand the provided file globs into a list of files, and process each
// one into an object containing that file's markdown tokens
return grunt.file.expand( files ).map( readAndTokenize );
} | javascript | function tokenizeMarkdownFromFiles( files, filterParams ) {
/**
* Read in the provided file and return its contents as markdown tokens
*
* @param {String} file A file path to read in
* @return {Array} An array of the individual markdown tokens found
* within the provided list of files
*/
function readAndTokenize( file ) {
// Read the file
var fileContents = grunt.file.read( file );
// Map file into an object defining the tokens for this file
return {
file: file,
tokens: convertToTokens( fileContents, filterParams )
};
}
// Expand the provided file globs into a list of files, and process each
// one into an object containing that file's markdown tokens
return grunt.file.expand( files ).map( readAndTokenize );
} | [
"function",
"tokenizeMarkdownFromFiles",
"(",
"files",
",",
"filterParams",
")",
"{",
"function",
"readAndTokenize",
"(",
"file",
")",
"{",
"var",
"fileContents",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"file",
")",
";",
"return",
"{",
"file",
":",
"file",
",",
"tokens",
":",
"convertToTokens",
"(",
"fileContents",
",",
"filterParams",
")",
"}",
";",
"}",
"return",
"grunt",
".",
"file",
".",
"expand",
"(",
"files",
")",
".",
"map",
"(",
"readAndTokenize",
")",
";",
"}"
] | Get an array of markdown tokens per file from an array of files, optionally
filtered to only those tokens matching a particular set of attributes
@example
var tokenizeMarkdown = require( 'tokenize-markdown' );
// Get all tokens
var tokens = tokenizeMarkdown.fromFiles( [ 'slides/*.md' ] );
// Get only tokens of type "code" and lang "javascript"
var jsTokens = tokenizeMarkdown.fromFiles( [ 'slides/*.md' ], {
type: 'code',
lang: 'javascript'
});
// Get tokens of lang "javascript" or "html", using a regex
var jsOrHtmlTokens = tokenizeMarkdown.fromFiles( [ 'slides/*.md' ], {
lang: /(javascript|html)/
});
@method fromFiles
@param {Array} files Array of file sources to expand and process
@param {Object} [filterParams] Optional hash of properties to use to filter
the returned tokens
@return {Array} Array of token objects | [
"Get",
"an",
"array",
"of",
"markdown",
"tokens",
"per",
"file",
"from",
"an",
"array",
"of",
"files",
"optionally",
"filtered",
"to",
"only",
"those",
"tokens",
"matching",
"a",
"particular",
"set",
"of",
"attributes"
] | ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0 | https://github.com/kadamwhite/tokenize-markdown/blob/ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0/tokenize-markdown.js#L107-L129 | train |
kadamwhite/tokenize-markdown | tokenize-markdown.js | readAndTokenize | function readAndTokenize( file ) {
// Read the file
var fileContents = grunt.file.read( file );
// Map file into an object defining the tokens for this file
return {
file: file,
tokens: convertToTokens( fileContents, filterParams )
};
} | javascript | function readAndTokenize( file ) {
// Read the file
var fileContents = grunt.file.read( file );
// Map file into an object defining the tokens for this file
return {
file: file,
tokens: convertToTokens( fileContents, filterParams )
};
} | [
"function",
"readAndTokenize",
"(",
"file",
")",
"{",
"var",
"fileContents",
"=",
"grunt",
".",
"file",
".",
"read",
"(",
"file",
")",
";",
"return",
"{",
"file",
":",
"file",
",",
"tokens",
":",
"convertToTokens",
"(",
"fileContents",
",",
"filterParams",
")",
"}",
";",
"}"
] | Read in the provided file and return its contents as markdown tokens
@param {String} file A file path to read in
@return {Array} An array of the individual markdown tokens found
within the provided list of files | [
"Read",
"in",
"the",
"provided",
"file",
"and",
"return",
"its",
"contents",
"as",
"markdown",
"tokens"
] | ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0 | https://github.com/kadamwhite/tokenize-markdown/blob/ecc08f4d71edb6c834ca223e0f25761f6e1ef4c0/tokenize-markdown.js#L115-L124 | train |
switer/muxjs | lib/mux.js | MuxFactory | function MuxFactory(options) {
function Class (receiveProps) {
Ctor.call(this, options, receiveProps)
}
Class.prototype = Object.create(Mux.prototype)
return Class
} | javascript | function MuxFactory(options) {
function Class (receiveProps) {
Ctor.call(this, options, receiveProps)
}
Class.prototype = Object.create(Mux.prototype)
return Class
} | [
"function",
"MuxFactory",
"(",
"options",
")",
"{",
"function",
"Class",
"(",
"receiveProps",
")",
"{",
"Ctor",
".",
"call",
"(",
"this",
",",
"options",
",",
"receiveProps",
")",
"}",
"Class",
".",
"prototype",
"=",
"Object",
".",
"create",
"(",
"Mux",
".",
"prototype",
")",
"return",
"Class",
"}"
] | Mux model factory
@private | [
"Mux",
"model",
"factory"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L77-L84 | train |
switer/muxjs | lib/mux.js | _defPrivateProperty | function _defPrivateProperty(name, value) {
if (instanceOf(value, Function)) value = value.bind(model)
_privateProperties[name] = value
$util.def(model, name, {
enumerable: false,
value: value
})
} | javascript | function _defPrivateProperty(name, value) {
if (instanceOf(value, Function)) value = value.bind(model)
_privateProperties[name] = value
$util.def(model, name, {
enumerable: false,
value: value
})
} | [
"function",
"_defPrivateProperty",
"(",
"name",
",",
"value",
")",
"{",
"if",
"(",
"instanceOf",
"(",
"value",
",",
"Function",
")",
")",
"value",
"=",
"value",
".",
"bind",
"(",
"model",
")",
"_privateProperties",
"[",
"name",
"]",
"=",
"value",
"$util",
".",
"def",
"(",
"model",
",",
"name",
",",
"{",
"enumerable",
":",
"false",
",",
"value",
":",
"value",
"}",
")",
"}"
] | define priavate property of the instance object | [
"define",
"priavate",
"property",
"of",
"the",
"instance",
"object"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L113-L120 | train |
switer/muxjs | lib/mux.js | _emitChange | function _emitChange(propname/*, arg1, ..., argX*/) {
var args = arguments
var kp = $normalize($join(_rootPath(), propname))
args[0] = CHANGE_EVENT + ':' + kp
_emitter.emit(CHANGE_EVENT, kp)
emitter.emit.apply(emitter, args)
args = $util.copyArray(args)
args[0] = kp
args.unshift('*')
emitter.emit.apply(emitter, args)
} | javascript | function _emitChange(propname/*, arg1, ..., argX*/) {
var args = arguments
var kp = $normalize($join(_rootPath(), propname))
args[0] = CHANGE_EVENT + ':' + kp
_emitter.emit(CHANGE_EVENT, kp)
emitter.emit.apply(emitter, args)
args = $util.copyArray(args)
args[0] = kp
args.unshift('*')
emitter.emit.apply(emitter, args)
} | [
"function",
"_emitChange",
"(",
"propname",
")",
"{",
"var",
"args",
"=",
"arguments",
"var",
"kp",
"=",
"$normalize",
"(",
"$join",
"(",
"_rootPath",
"(",
")",
",",
"propname",
")",
")",
"args",
"[",
"0",
"]",
"=",
"CHANGE_EVENT",
"+",
"':'",
"+",
"kp",
"_emitter",
".",
"emit",
"(",
"CHANGE_EVENT",
",",
"kp",
")",
"emitter",
".",
"emit",
".",
"apply",
"(",
"emitter",
",",
"args",
")",
"args",
"=",
"$util",
".",
"copyArray",
"(",
"args",
")",
"args",
"[",
"0",
"]",
"=",
"kp",
"args",
".",
"unshift",
"(",
"'*'",
")",
"emitter",
".",
"emit",
".",
"apply",
"(",
"emitter",
",",
"args",
")",
"}"
] | local proxy for EventEmitter | [
"local",
"proxy",
"for",
"EventEmitter"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L204-L215 | train |
switer/muxjs | lib/mux.js | _prop2CptDepsMapping | function _prop2CptDepsMapping (propname, dep) {
// if ($indexOf(_computedKeys, dep))
// return $warn('Dependency should not computed property')
$util.patch(_cptDepsMapping, dep, [])
var dest = _cptDepsMapping[dep]
if ($indexOf(dest, propname)) return
dest.push(propname)
} | javascript | function _prop2CptDepsMapping (propname, dep) {
// if ($indexOf(_computedKeys, dep))
// return $warn('Dependency should not computed property')
$util.patch(_cptDepsMapping, dep, [])
var dest = _cptDepsMapping[dep]
if ($indexOf(dest, propname)) return
dest.push(propname)
} | [
"function",
"_prop2CptDepsMapping",
"(",
"propname",
",",
"dep",
")",
"{",
"$util",
".",
"patch",
"(",
"_cptDepsMapping",
",",
"dep",
",",
"[",
"]",
")",
"var",
"dest",
"=",
"_cptDepsMapping",
"[",
"dep",
"]",
"if",
"(",
"$indexOf",
"(",
"dest",
",",
"propname",
")",
")",
"return",
"dest",
".",
"push",
"(",
"propname",
")",
"}"
] | Add dependence to "_cptDepsMapping"
@param propname <String> property name
@param dep <String> dependency name | [
"Add",
"dependence",
"to",
"_cptDepsMapping"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L221-L229 | train |
switer/muxjs | lib/mux.js | _subInstance | function _subInstance (target, props, kp) {
var ins
var _mux = target.__mux__
if (_mux && _mux.__kp__ === kp && _mux.__root__ === __muxid__) {
// reuse
ins = target
// emitter proxy
ins._$emitter(emitter)
// a private emitter for communication between instances
ins._$_emitter(_emitter)
} else {
ins = new Mux({
props: props,
emitter: emitter,
_emitter: _emitter,
__kp__: kp
})
}
if (!ins.__root__) {
$util.def(ins, '__root__', {
enumerable: false,
value: __muxid__
})
}
return ins
} | javascript | function _subInstance (target, props, kp) {
var ins
var _mux = target.__mux__
if (_mux && _mux.__kp__ === kp && _mux.__root__ === __muxid__) {
// reuse
ins = target
// emitter proxy
ins._$emitter(emitter)
// a private emitter for communication between instances
ins._$_emitter(_emitter)
} else {
ins = new Mux({
props: props,
emitter: emitter,
_emitter: _emitter,
__kp__: kp
})
}
if (!ins.__root__) {
$util.def(ins, '__root__', {
enumerable: false,
value: __muxid__
})
}
return ins
} | [
"function",
"_subInstance",
"(",
"target",
",",
"props",
",",
"kp",
")",
"{",
"var",
"ins",
"var",
"_mux",
"=",
"target",
".",
"__mux__",
"if",
"(",
"_mux",
"&&",
"_mux",
".",
"__kp__",
"===",
"kp",
"&&",
"_mux",
".",
"__root__",
"===",
"__muxid__",
")",
"{",
"ins",
"=",
"target",
"ins",
".",
"_$emitter",
"(",
"emitter",
")",
"ins",
".",
"_$_emitter",
"(",
"_emitter",
")",
"}",
"else",
"{",
"ins",
"=",
"new",
"Mux",
"(",
"{",
"props",
":",
"props",
",",
"emitter",
":",
"emitter",
",",
"_emitter",
":",
"_emitter",
",",
"__kp__",
":",
"kp",
"}",
")",
"}",
"if",
"(",
"!",
"ins",
".",
"__root__",
")",
"{",
"$util",
".",
"def",
"(",
"ins",
",",
"'__root__'",
",",
"{",
"enumerable",
":",
"false",
",",
"value",
":",
"__muxid__",
"}",
")",
"}",
"return",
"ins",
"}"
] | Instance or reuse a sub-mux-instance with specified keyPath and emitter
@param target <Object> instance target, it could be a Mux instance
@param props <Object> property value that has been walked
@param kp <String> keyPath of target, use to diff instance keyPath changes or instance with the keyPath | [
"Instance",
"or",
"reuse",
"a",
"sub",
"-",
"mux",
"-",
"instance",
"with",
"specified",
"keyPath",
"and",
"emitter"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L236-L262 | train |
switer/muxjs | lib/mux.js | _walk | function _walk (name, value, mountedPath) {
var tov = $type(value) // type of value
// initial path prefix is root path
var kp = mountedPath ? mountedPath : $join(_rootPath(), name)
/**
* Array methods hook
*/
if (tov == ARRAY) {
$arrayHook(value, function (self, methodName, nativeMethod, args) {
var pv = $util.copyArray(self)
var result = nativeMethod.apply(self, args)
// set value directly after walk
_props[name] = _walk(name, self, kp)
if (methodName == 'splice') {
_emitChange(kp, self, pv, methodName, args)
} else {
_emitChange(kp, self, pv, methodName)
}
return result
})
}
// deep observe into each property value
switch(tov) {
case OBJECT:
// walk deep into object items
var props = {}
var obj = value
if (instanceOf(value, Mux)) obj = value.$props()
$util.objEach(obj, function (k, v) {
props[k] = _walk(k, v, $join(kp, k))
})
return _subInstance(value, props, kp)
case ARRAY:
// walk deep into array items
value.forEach(function (item, index) {
value[index] = _walk(index, item, $join(kp, index))
})
return value
default:
return value
}
} | javascript | function _walk (name, value, mountedPath) {
var tov = $type(value) // type of value
// initial path prefix is root path
var kp = mountedPath ? mountedPath : $join(_rootPath(), name)
/**
* Array methods hook
*/
if (tov == ARRAY) {
$arrayHook(value, function (self, methodName, nativeMethod, args) {
var pv = $util.copyArray(self)
var result = nativeMethod.apply(self, args)
// set value directly after walk
_props[name] = _walk(name, self, kp)
if (methodName == 'splice') {
_emitChange(kp, self, pv, methodName, args)
} else {
_emitChange(kp, self, pv, methodName)
}
return result
})
}
// deep observe into each property value
switch(tov) {
case OBJECT:
// walk deep into object items
var props = {}
var obj = value
if (instanceOf(value, Mux)) obj = value.$props()
$util.objEach(obj, function (k, v) {
props[k] = _walk(k, v, $join(kp, k))
})
return _subInstance(value, props, kp)
case ARRAY:
// walk deep into array items
value.forEach(function (item, index) {
value[index] = _walk(index, item, $join(kp, index))
})
return value
default:
return value
}
} | [
"function",
"_walk",
"(",
"name",
",",
"value",
",",
"mountedPath",
")",
"{",
"var",
"tov",
"=",
"$type",
"(",
"value",
")",
"var",
"kp",
"=",
"mountedPath",
"?",
"mountedPath",
":",
"$join",
"(",
"_rootPath",
"(",
")",
",",
"name",
")",
"if",
"(",
"tov",
"==",
"ARRAY",
")",
"{",
"$arrayHook",
"(",
"value",
",",
"function",
"(",
"self",
",",
"methodName",
",",
"nativeMethod",
",",
"args",
")",
"{",
"var",
"pv",
"=",
"$util",
".",
"copyArray",
"(",
"self",
")",
"var",
"result",
"=",
"nativeMethod",
".",
"apply",
"(",
"self",
",",
"args",
")",
"_props",
"[",
"name",
"]",
"=",
"_walk",
"(",
"name",
",",
"self",
",",
"kp",
")",
"if",
"(",
"methodName",
"==",
"'splice'",
")",
"{",
"_emitChange",
"(",
"kp",
",",
"self",
",",
"pv",
",",
"methodName",
",",
"args",
")",
"}",
"else",
"{",
"_emitChange",
"(",
"kp",
",",
"self",
",",
"pv",
",",
"methodName",
")",
"}",
"return",
"result",
"}",
")",
"}",
"switch",
"(",
"tov",
")",
"{",
"case",
"OBJECT",
":",
"var",
"props",
"=",
"{",
"}",
"var",
"obj",
"=",
"value",
"if",
"(",
"instanceOf",
"(",
"value",
",",
"Mux",
")",
")",
"obj",
"=",
"value",
".",
"$props",
"(",
")",
"$util",
".",
"objEach",
"(",
"obj",
",",
"function",
"(",
"k",
",",
"v",
")",
"{",
"props",
"[",
"k",
"]",
"=",
"_walk",
"(",
"k",
",",
"v",
",",
"$join",
"(",
"kp",
",",
"k",
")",
")",
"}",
")",
"return",
"_subInstance",
"(",
"value",
",",
"props",
",",
"kp",
")",
"case",
"ARRAY",
":",
"value",
".",
"forEach",
"(",
"function",
"(",
"item",
",",
"index",
")",
"{",
"value",
"[",
"index",
"]",
"=",
"_walk",
"(",
"index",
",",
"item",
",",
"$join",
"(",
"kp",
",",
"index",
")",
")",
"}",
")",
"return",
"value",
"default",
":",
"return",
"value",
"}",
"}"
] | A hook method for setting value to "_props"
@param name <String> property name
@param value
@param mountedPath <String> property's value mouted path | [
"A",
"hook",
"method",
"for",
"setting",
"value",
"to",
"_props"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L270-L312 | train |
switer/muxjs | lib/mux.js | _$set | function _$set(kp, value, lazyEmit) {
if (_destroy) return _destroyNotice()
return _$sync(kp, value, lazyEmit)
// if (!diff) return
/**
* Base type change of object type will be trigger change event
* next and pre value are not keypath value but property value
*/
// if ( kp == diff.mounted && $util.diff(diff.next, diff.pre) ) {
// var propname = diff.mounted
// // emit change immediately
// _emitChange(propname, diff.next, diff.pre)
// }
} | javascript | function _$set(kp, value, lazyEmit) {
if (_destroy) return _destroyNotice()
return _$sync(kp, value, lazyEmit)
// if (!diff) return
/**
* Base type change of object type will be trigger change event
* next and pre value are not keypath value but property value
*/
// if ( kp == diff.mounted && $util.diff(diff.next, diff.pre) ) {
// var propname = diff.mounted
// // emit change immediately
// _emitChange(propname, diff.next, diff.pre)
// }
} | [
"function",
"_$set",
"(",
"kp",
",",
"value",
",",
"lazyEmit",
")",
"{",
"if",
"(",
"_destroy",
")",
"return",
"_destroyNotice",
"(",
")",
"return",
"_$sync",
"(",
"kp",
",",
"value",
",",
"lazyEmit",
")",
"}"
] | sync props value and trigger change event
@param kp <String> keyPath | [
"sync",
"props",
"value",
"and",
"trigger",
"change",
"event"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L374-L388 | train |
switer/muxjs | lib/mux.js | _$setMulti | function _$setMulti(keyMap) {
if (_destroy) return _destroyNotice()
if (!keyMap || $type(keyMap) != OBJECT) return
var changes = []
$util.objEach(keyMap, function (key, item) {
var cg = _$set(key, item, true)
if (cg) changes.push(cg)
})
changes.forEach(function (args) {
_emitChange.apply(null, args)
})
} | javascript | function _$setMulti(keyMap) {
if (_destroy) return _destroyNotice()
if (!keyMap || $type(keyMap) != OBJECT) return
var changes = []
$util.objEach(keyMap, function (key, item) {
var cg = _$set(key, item, true)
if (cg) changes.push(cg)
})
changes.forEach(function (args) {
_emitChange.apply(null, args)
})
} | [
"function",
"_$setMulti",
"(",
"keyMap",
")",
"{",
"if",
"(",
"_destroy",
")",
"return",
"_destroyNotice",
"(",
")",
"if",
"(",
"!",
"keyMap",
"||",
"$type",
"(",
"keyMap",
")",
"!=",
"OBJECT",
")",
"return",
"var",
"changes",
"=",
"[",
"]",
"$util",
".",
"objEach",
"(",
"keyMap",
",",
"function",
"(",
"key",
",",
"item",
")",
"{",
"var",
"cg",
"=",
"_$set",
"(",
"key",
",",
"item",
",",
"true",
")",
"if",
"(",
"cg",
")",
"changes",
".",
"push",
"(",
"cg",
")",
"}",
")",
"changes",
".",
"forEach",
"(",
"function",
"(",
"args",
")",
"{",
"_emitChange",
".",
"apply",
"(",
"null",
",",
"args",
")",
"}",
")",
"}"
] | sync props's value in batch and trigger change event
@param keyMap <Object> properties object | [
"sync",
"props",
"s",
"value",
"in",
"batch",
"and",
"trigger",
"change",
"event"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L394-L407 | train |
switer/muxjs | lib/mux.js | _$add | function _$add(prop, value, lazyEmit) {
if (prop.match(/[\.\[\]]/)) {
throw new Error('Propname shoudn\'t contains "." or "[" or "]"')
}
if ($indexOf(_observableKeys, prop)) {
// If value is specified, reset value
return arguments.length > 1 ? true : false
}
_props[prop] = _walk(prop, $util.copyValue(value))
_observableKeys.push(prop)
$util.def(model, prop, {
enumerable: true,
get: function() {
return _props[prop]
},
set: function (v) {
_$set(prop, v)
}
})
// add peroperty will trigger change event
if (!lazyEmit) {
_emitChange(prop, value)
} else {
return {
kp: prop,
vl: value
}
}
} | javascript | function _$add(prop, value, lazyEmit) {
if (prop.match(/[\.\[\]]/)) {
throw new Error('Propname shoudn\'t contains "." or "[" or "]"')
}
if ($indexOf(_observableKeys, prop)) {
// If value is specified, reset value
return arguments.length > 1 ? true : false
}
_props[prop] = _walk(prop, $util.copyValue(value))
_observableKeys.push(prop)
$util.def(model, prop, {
enumerable: true,
get: function() {
return _props[prop]
},
set: function (v) {
_$set(prop, v)
}
})
// add peroperty will trigger change event
if (!lazyEmit) {
_emitChange(prop, value)
} else {
return {
kp: prop,
vl: value
}
}
} | [
"function",
"_$add",
"(",
"prop",
",",
"value",
",",
"lazyEmit",
")",
"{",
"if",
"(",
"prop",
".",
"match",
"(",
"/",
"[\\.\\[\\]]",
"/",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Propname shoudn\\'t contains \".\" or \"[\" or \"]\"'",
")",
"}",
"\\'",
"if",
"(",
"$indexOf",
"(",
"_observableKeys",
",",
"prop",
")",
")",
"{",
"return",
"arguments",
".",
"length",
">",
"1",
"?",
"true",
":",
"false",
"}",
"_props",
"[",
"prop",
"]",
"=",
"_walk",
"(",
"prop",
",",
"$util",
".",
"copyValue",
"(",
"value",
")",
")",
"_observableKeys",
".",
"push",
"(",
"prop",
")",
"$util",
".",
"def",
"(",
"model",
",",
"prop",
",",
"{",
"enumerable",
":",
"true",
",",
"get",
":",
"function",
"(",
")",
"{",
"return",
"_props",
"[",
"prop",
"]",
"}",
",",
"set",
":",
"function",
"(",
"v",
")",
"{",
"_$set",
"(",
"prop",
",",
"v",
")",
"}",
"}",
")",
"}"
] | create a prop observer if not in observer,
return true if no value setting.
@param prop <String> property name
@param value property value | [
"create",
"a",
"prop",
"observer",
"if",
"not",
"in",
"observer",
"return",
"true",
"if",
"no",
"value",
"setting",
"."
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L415-L444 | train |
switer/muxjs | lib/mux.js | _walkResetEmiter | function _walkResetEmiter (ins, em, _pem) {
if ($type(ins) == OBJECT) {
var items = ins
if (instanceOf(ins, Mux)) {
ins._$emitter(em, _pem)
items = ins.$props()
}
$util.objEach(items, function (k, v) {
_walkResetEmiter(v, em, _pem)
})
} else if ($type(ins) == ARRAY) {
ins.forEach(function (v) {
_walkResetEmiter(v, em, _pem)
})
}
} | javascript | function _walkResetEmiter (ins, em, _pem) {
if ($type(ins) == OBJECT) {
var items = ins
if (instanceOf(ins, Mux)) {
ins._$emitter(em, _pem)
items = ins.$props()
}
$util.objEach(items, function (k, v) {
_walkResetEmiter(v, em, _pem)
})
} else if ($type(ins) == ARRAY) {
ins.forEach(function (v) {
_walkResetEmiter(v, em, _pem)
})
}
} | [
"function",
"_walkResetEmiter",
"(",
"ins",
",",
"em",
",",
"_pem",
")",
"{",
"if",
"(",
"$type",
"(",
"ins",
")",
"==",
"OBJECT",
")",
"{",
"var",
"items",
"=",
"ins",
"if",
"(",
"instanceOf",
"(",
"ins",
",",
"Mux",
")",
")",
"{",
"ins",
".",
"_$emitter",
"(",
"em",
",",
"_pem",
")",
"items",
"=",
"ins",
".",
"$props",
"(",
")",
"}",
"$util",
".",
"objEach",
"(",
"items",
",",
"function",
"(",
"k",
",",
"v",
")",
"{",
"_walkResetEmiter",
"(",
"v",
",",
"em",
",",
"_pem",
")",
"}",
")",
"}",
"else",
"if",
"(",
"$type",
"(",
"ins",
")",
"==",
"ARRAY",
")",
"{",
"ins",
".",
"forEach",
"(",
"function",
"(",
"v",
")",
"{",
"_walkResetEmiter",
"(",
"v",
",",
"em",
",",
"_pem",
")",
"}",
")",
"}",
"}"
] | Reset emitter of the instance recursively
@param ins <Mux> | [
"Reset",
"emitter",
"of",
"the",
"instance",
"recursively"
] | bc272efa32572c63be813bb7ce083879c6dc7266 | https://github.com/switer/muxjs/blob/bc272efa32572c63be813bb7ce083879c6dc7266/lib/mux.js#L758-L773 | train |
hightail/smartling-sdk | smartling.js | function (apiBaseUrl, apiKey, projectId) {
this.config = {
apiBaseUrl: apiBaseUrl,
apiKey: apiKey,
projectId: projectId
};
} | javascript | function (apiBaseUrl, apiKey, projectId) {
this.config = {
apiBaseUrl: apiBaseUrl,
apiKey: apiKey,
projectId: projectId
};
} | [
"function",
"(",
"apiBaseUrl",
",",
"apiKey",
",",
"projectId",
")",
"{",
"this",
".",
"config",
"=",
"{",
"apiBaseUrl",
":",
"apiBaseUrl",
",",
"apiKey",
":",
"apiKey",
",",
"projectId",
":",
"projectId",
"}",
";",
"}"
] | Initializes Smartling with the given params
@param baseUrl
@param apiKey
@param projectId | [
"Initializes",
"Smartling",
"with",
"the",
"given",
"params"
] | 08a15c4eed1ee842bf00c82f80ade4cada91b9a5 | https://github.com/hightail/smartling-sdk/blob/08a15c4eed1ee842bf00c82f80ade4cada91b9a5/smartling.js#L107-L113 | train |
|
tadam313/sheet-db | index.js | connect | function connect(sheetId, options) {
options = options || {};
// TODO: needs better access token handling
let api = apiFactory.getApi(options.version);
let restClient = clientFactory({
token: options.token,
gApi: api,
gCache: cache
});
return new Spreadsheet(sheetId, restClient, options);
} | javascript | function connect(sheetId, options) {
options = options || {};
// TODO: needs better access token handling
let api = apiFactory.getApi(options.version);
let restClient = clientFactory({
token: options.token,
gApi: api,
gCache: cache
});
return new Spreadsheet(sheetId, restClient, options);
} | [
"function",
"connect",
"(",
"sheetId",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"let",
"api",
"=",
"apiFactory",
".",
"getApi",
"(",
"options",
".",
"version",
")",
";",
"let",
"restClient",
"=",
"clientFactory",
"(",
"{",
"token",
":",
"options",
".",
"token",
",",
"gApi",
":",
"api",
",",
"gCache",
":",
"cache",
"}",
")",
";",
"return",
"new",
"Spreadsheet",
"(",
"sheetId",
",",
"restClient",
",",
"options",
")",
";",
"}"
] | Connects and initializes the sheet db.
@param {string} sheetId - ID of the specific spreadsheet
@param {object} options - Optional options. | [
"Connects",
"and",
"initializes",
"the",
"sheet",
"db",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/index.js#L15-L28 | train |
chip-js/fragments-js | src/animated-binding.js | function(node, callback) {
if (node.firstViewNode) node = node.firstViewNode;
this.animateNode('out', node, callback);
} | javascript | function(node, callback) {
if (node.firstViewNode) node = node.firstViewNode;
this.animateNode('out', node, callback);
} | [
"function",
"(",
"node",
",",
"callback",
")",
"{",
"if",
"(",
"node",
".",
"firstViewNode",
")",
"node",
"=",
"node",
".",
"firstViewNode",
";",
"this",
".",
"animateNode",
"(",
"'out'",
",",
"node",
",",
"callback",
")",
";",
"}"
] | Helper method to remove a node from the DOM, allowing for animations to occur. `callback` will be called when
finished. | [
"Helper",
"method",
"to",
"remove",
"a",
"node",
"from",
"the",
"DOM",
"allowing",
"for",
"animations",
"to",
"occur",
".",
"callback",
"will",
"be",
"called",
"when",
"finished",
"."
] | 5d613ea42c3823423efb01fce4ffef80c7f5ce0f | https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/animated-binding.js#L88-L92 | train |
|
elcontraption/polylinear-scale | src/index.js | polylinearScale | function polylinearScale (domain, range, clamp) {
const domains = domain || [0, 1]
const ranges = range || [0, 1]
clamp = clamp || false
if (domains.length !== ranges.length) {
throw new Error('polylinearScale requires domain and range to have an equivalent number of values')
}
/**
* The compiled scale to return
*
* @param {Number} value The number to scale
* @return {Number} The result
*/
return function (value) {
var rangeMin
var rangeMax
var domain
var range
var ratio
var result
var i = 0
/* eslint-disable no-sequences */
while (i < domains.length - 1) {
if (value >= domains[i] && value <= domains[i + 1]) {
domain = [domains[i], domains[i + 1]],
range = [ranges[i], ranges[i + 1]]
break
}
i++
}
// Value is outside given domain
if (domain === undefined) {
if (value < domains[0]) {
domain = [domains[0], domains[1]]
range = [ranges[0], ranges[1]]
} else {
domain = [domains[domains.length - 2], domains[domains.length - 1]]
range = [ranges[ranges.length - 2], ranges[ranges.length - 1]]
}
}
ratio = (range[1] - range[0]) / (domain[1] - domain[0])
result = range[0] + ratio * (value - domain[0])
if (clamp) {
rangeMin = Math.min(range[0], range[1])
rangeMax = Math.max(range[0], range[1])
result = Math.min(rangeMax, Math.max(rangeMin, result))
}
return result
}
} | javascript | function polylinearScale (domain, range, clamp) {
const domains = domain || [0, 1]
const ranges = range || [0, 1]
clamp = clamp || false
if (domains.length !== ranges.length) {
throw new Error('polylinearScale requires domain and range to have an equivalent number of values')
}
/**
* The compiled scale to return
*
* @param {Number} value The number to scale
* @return {Number} The result
*/
return function (value) {
var rangeMin
var rangeMax
var domain
var range
var ratio
var result
var i = 0
/* eslint-disable no-sequences */
while (i < domains.length - 1) {
if (value >= domains[i] && value <= domains[i + 1]) {
domain = [domains[i], domains[i + 1]],
range = [ranges[i], ranges[i + 1]]
break
}
i++
}
// Value is outside given domain
if (domain === undefined) {
if (value < domains[0]) {
domain = [domains[0], domains[1]]
range = [ranges[0], ranges[1]]
} else {
domain = [domains[domains.length - 2], domains[domains.length - 1]]
range = [ranges[ranges.length - 2], ranges[ranges.length - 1]]
}
}
ratio = (range[1] - range[0]) / (domain[1] - domain[0])
result = range[0] + ratio * (value - domain[0])
if (clamp) {
rangeMin = Math.min(range[0], range[1])
rangeMax = Math.max(range[0], range[1])
result = Math.min(rangeMax, Math.max(rangeMin, result))
}
return result
}
} | [
"function",
"polylinearScale",
"(",
"domain",
",",
"range",
",",
"clamp",
")",
"{",
"const",
"domains",
"=",
"domain",
"||",
"[",
"0",
",",
"1",
"]",
"const",
"ranges",
"=",
"range",
"||",
"[",
"0",
",",
"1",
"]",
"clamp",
"=",
"clamp",
"||",
"false",
"if",
"(",
"domains",
".",
"length",
"!==",
"ranges",
".",
"length",
")",
"{",
"throw",
"new",
"Error",
"(",
"'polylinearScale requires domain and range to have an equivalent number of values'",
")",
"}",
"return",
"function",
"(",
"value",
")",
"{",
"var",
"rangeMin",
"var",
"rangeMax",
"var",
"domain",
"var",
"range",
"var",
"ratio",
"var",
"result",
"var",
"i",
"=",
"0",
"while",
"(",
"i",
"<",
"domains",
".",
"length",
"-",
"1",
")",
"{",
"if",
"(",
"value",
">=",
"domains",
"[",
"i",
"]",
"&&",
"value",
"<=",
"domains",
"[",
"i",
"+",
"1",
"]",
")",
"{",
"domain",
"=",
"[",
"domains",
"[",
"i",
"]",
",",
"domains",
"[",
"i",
"+",
"1",
"]",
"]",
",",
"range",
"=",
"[",
"ranges",
"[",
"i",
"]",
",",
"ranges",
"[",
"i",
"+",
"1",
"]",
"]",
"break",
"}",
"i",
"++",
"}",
"if",
"(",
"domain",
"===",
"undefined",
")",
"{",
"if",
"(",
"value",
"<",
"domains",
"[",
"0",
"]",
")",
"{",
"domain",
"=",
"[",
"domains",
"[",
"0",
"]",
",",
"domains",
"[",
"1",
"]",
"]",
"range",
"=",
"[",
"ranges",
"[",
"0",
"]",
",",
"ranges",
"[",
"1",
"]",
"]",
"}",
"else",
"{",
"domain",
"=",
"[",
"domains",
"[",
"domains",
".",
"length",
"-",
"2",
"]",
",",
"domains",
"[",
"domains",
".",
"length",
"-",
"1",
"]",
"]",
"range",
"=",
"[",
"ranges",
"[",
"ranges",
".",
"length",
"-",
"2",
"]",
",",
"ranges",
"[",
"ranges",
".",
"length",
"-",
"1",
"]",
"]",
"}",
"}",
"ratio",
"=",
"(",
"range",
"[",
"1",
"]",
"-",
"range",
"[",
"0",
"]",
")",
"/",
"(",
"domain",
"[",
"1",
"]",
"-",
"domain",
"[",
"0",
"]",
")",
"result",
"=",
"range",
"[",
"0",
"]",
"+",
"ratio",
"*",
"(",
"value",
"-",
"domain",
"[",
"0",
"]",
")",
"if",
"(",
"clamp",
")",
"{",
"rangeMin",
"=",
"Math",
".",
"min",
"(",
"range",
"[",
"0",
"]",
",",
"range",
"[",
"1",
"]",
")",
"rangeMax",
"=",
"Math",
".",
"max",
"(",
"range",
"[",
"0",
"]",
",",
"range",
"[",
"1",
"]",
")",
"result",
"=",
"Math",
".",
"min",
"(",
"rangeMax",
",",
"Math",
".",
"max",
"(",
"rangeMin",
",",
"result",
")",
")",
"}",
"return",
"result",
"}",
"}"
] | A polylinear scale
Supports multiple piecewise linear scales that divide a continuous domain and range.
@param {Array} domain Two or more numbers
@param {Array} range Numbers equivalent to number in `domain`
@param {Boolean} clamp Enables or disables clamping
@return {Function} Scale function | [
"A",
"polylinear",
"scale"
] | 1cf6b0e710932eba7bf97f334ce0dc24c001b872 | https://github.com/elcontraption/polylinear-scale/blob/1cf6b0e710932eba7bf97f334ce0dc24c001b872/src/index.js#L11-L67 | train |
lddubeau/bluejax | index.js | inherit | function inherit(inheritor, inherited) {
inheritor.prototype = Object.create(inherited.prototype);
inheritor.prototype.constructor = inheritor;
} | javascript | function inherit(inheritor, inherited) {
inheritor.prototype = Object.create(inherited.prototype);
inheritor.prototype.constructor = inheritor;
} | [
"function",
"inherit",
"(",
"inheritor",
",",
"inherited",
")",
"{",
"inheritor",
".",
"prototype",
"=",
"Object",
".",
"create",
"(",
"inherited",
".",
"prototype",
")",
";",
"inheritor",
".",
"prototype",
".",
"constructor",
"=",
"inheritor",
";",
"}"
] | Utility function for class inheritance. | [
"Utility",
"function",
"for",
"class",
"inheritance",
"."
] | 106359491ba707b5bb22b3b5b84cedca08555ff8 | https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L26-L29 | train |
lddubeau/bluejax | index.js | rename | function rename(cls, name) {
try {
Object.defineProperty(cls, "name", { value: name });
}
catch (ex) {
// Trying to defineProperty on `name` fails on Safari with a TypeError.
if (!(ex instanceof TypeError)) {
throw ex;
}
}
cls.prototype.name = name;
} | javascript | function rename(cls, name) {
try {
Object.defineProperty(cls, "name", { value: name });
}
catch (ex) {
// Trying to defineProperty on `name` fails on Safari with a TypeError.
if (!(ex instanceof TypeError)) {
throw ex;
}
}
cls.prototype.name = name;
} | [
"function",
"rename",
"(",
"cls",
",",
"name",
")",
"{",
"try",
"{",
"Object",
".",
"defineProperty",
"(",
"cls",
",",
"\"name\"",
",",
"{",
"value",
":",
"name",
"}",
")",
";",
"}",
"catch",
"(",
"ex",
")",
"{",
"if",
"(",
"!",
"(",
"ex",
"instanceof",
"TypeError",
")",
")",
"{",
"throw",
"ex",
";",
"}",
"}",
"cls",
".",
"prototype",
".",
"name",
"=",
"name",
";",
"}"
] | Utility function for classes that are derived from Error. The prototype name is initially set to some generic value which is not particularly useful. This fixes the problem. We have to pass an explicit string through `name` because on some platforms we cannot count on `cls.name`. | [
"Utility",
"function",
"for",
"classes",
"that",
"are",
"derived",
"from",
"Error",
".",
"The",
"prototype",
"name",
"is",
"initially",
"set",
"to",
"some",
"generic",
"value",
"which",
"is",
"not",
"particularly",
"useful",
".",
"This",
"fixes",
"the",
"problem",
".",
"We",
"have",
"to",
"pass",
"an",
"explicit",
"string",
"through",
"name",
"because",
"on",
"some",
"platforms",
"we",
"cannot",
"count",
"on",
"cls",
".",
"name",
"."
] | 106359491ba707b5bb22b3b5b84cedca08555ff8 | https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L35-L46 | train |
lddubeau/bluejax | index.js | makeError | function makeError(jqXHR, textStatus, errorThrown, options) {
var Constructor = statusToError[textStatus];
// We did not find anything in the map, which would happen if the textStatus
// was "error". Determine whether an ``HttpError`` or an ``AjaxError`` must
// be thrown.
if (!Constructor) {
Constructor = statusToError[(jqXHR.status !== 0) ? "http" : "ajax"];
}
return new Constructor(jqXHR, textStatus, errorThrown, options);
} | javascript | function makeError(jqXHR, textStatus, errorThrown, options) {
var Constructor = statusToError[textStatus];
// We did not find anything in the map, which would happen if the textStatus
// was "error". Determine whether an ``HttpError`` or an ``AjaxError`` must
// be thrown.
if (!Constructor) {
Constructor = statusToError[(jqXHR.status !== 0) ? "http" : "ajax"];
}
return new Constructor(jqXHR, textStatus, errorThrown, options);
} | [
"function",
"makeError",
"(",
"jqXHR",
",",
"textStatus",
",",
"errorThrown",
",",
"options",
")",
"{",
"var",
"Constructor",
"=",
"statusToError",
"[",
"textStatus",
"]",
";",
"if",
"(",
"!",
"Constructor",
")",
"{",
"Constructor",
"=",
"statusToError",
"[",
"(",
"jqXHR",
".",
"status",
"!==",
"0",
")",
"?",
"\"http\"",
":",
"\"ajax\"",
"]",
";",
"}",
"return",
"new",
"Constructor",
"(",
"jqXHR",
",",
"textStatus",
",",
"errorThrown",
",",
"options",
")",
";",
"}"
] | Given a ``jqXHR`` that failed, create an error object. | [
"Given",
"a",
"jqXHR",
"that",
"failed",
"create",
"an",
"error",
"object",
"."
] | 106359491ba707b5bb22b3b5b84cedca08555ff8 | https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L150-L161 | train |
lddubeau/bluejax | index.js | connectionCheck | function connectionCheck(error, diagnose) {
var servers = diagnose.knownServers;
// Nothing to check so we fail immediately.
if (!servers || servers.length === 0) {
throw new ServerDownError(error);
}
// We check all the servers that the user asked to check. If none respond,
// we blame the network. Otherwise, we blame the server.
return Promise.all(servers.map(function urlToAjax(url) {
// eslint-disable-next-line no-use-before-define
return ajax({ url: dedupURL(normalizeURL(url)), timeout: 1000 })
.reflect();
})).filter(function filterSuccessfulServers(result) {
return result.isFulfilled();
}).then(function checkAnyFullfilled(fulfilled) {
if (fulfilled.length === 0) {
throw new NetworkDownError(error);
}
throw new ServerDownError(error);
});
} | javascript | function connectionCheck(error, diagnose) {
var servers = diagnose.knownServers;
// Nothing to check so we fail immediately.
if (!servers || servers.length === 0) {
throw new ServerDownError(error);
}
// We check all the servers that the user asked to check. If none respond,
// we blame the network. Otherwise, we blame the server.
return Promise.all(servers.map(function urlToAjax(url) {
// eslint-disable-next-line no-use-before-define
return ajax({ url: dedupURL(normalizeURL(url)), timeout: 1000 })
.reflect();
})).filter(function filterSuccessfulServers(result) {
return result.isFulfilled();
}).then(function checkAnyFullfilled(fulfilled) {
if (fulfilled.length === 0) {
throw new NetworkDownError(error);
}
throw new ServerDownError(error);
});
} | [
"function",
"connectionCheck",
"(",
"error",
",",
"diagnose",
")",
"{",
"var",
"servers",
"=",
"diagnose",
".",
"knownServers",
";",
"if",
"(",
"!",
"servers",
"||",
"servers",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"ServerDownError",
"(",
"error",
")",
";",
"}",
"return",
"Promise",
".",
"all",
"(",
"servers",
".",
"map",
"(",
"function",
"urlToAjax",
"(",
"url",
")",
"{",
"return",
"ajax",
"(",
"{",
"url",
":",
"dedupURL",
"(",
"normalizeURL",
"(",
"url",
")",
")",
",",
"timeout",
":",
"1000",
"}",
")",
".",
"reflect",
"(",
")",
";",
"}",
")",
")",
".",
"filter",
"(",
"function",
"filterSuccessfulServers",
"(",
"result",
")",
"{",
"return",
"result",
".",
"isFulfilled",
"(",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"checkAnyFullfilled",
"(",
"fulfilled",
")",
"{",
"if",
"(",
"fulfilled",
".",
"length",
"===",
"0",
")",
"{",
"throw",
"new",
"NetworkDownError",
"(",
"error",
")",
";",
"}",
"throw",
"new",
"ServerDownError",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
] | This is called once we know a) the browser is not offline but b) we cannot reach the server that should serve our request. | [
"This",
"is",
"called",
"once",
"we",
"know",
"a",
")",
"the",
"browser",
"is",
"not",
"offline",
"but",
"b",
")",
"we",
"cannot",
"reach",
"the",
"server",
"that",
"should",
"serve",
"our",
"request",
"."
] | 106359491ba707b5bb22b3b5b84cedca08555ff8 | https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L250-L273 | train |
lddubeau/bluejax | index.js | diagnoseIt | function diagnoseIt(error, diagnose) {
// The browser reports being offline, blame the problem on this.
if (("onLine" in navigator) && !navigator.onLine) {
throw new BrowserOfflineError(error);
}
var serverURL = diagnose.serverURL;
var check;
// If the user gave us a server URL to check whether the server is up at
// all, use it. If that failed, then we need to check the connection. If we
// do not have a server URL, then we need to check the connection right
// away.
if (serverURL) {
// eslint-disable-next-line no-use-before-define
check = ajax({ url: dedupURL(normalizeURL(serverURL)) })
.catch(function failed() {
return connectionCheck(error, diagnose);
});
}
else {
check = connectionCheck(error, diagnose);
}
return check.then(function success() {
// All of our checks passed... and we have no tries left, so just rethrow
// what we would have thrown in the first place.
throw error;
});
} | javascript | function diagnoseIt(error, diagnose) {
// The browser reports being offline, blame the problem on this.
if (("onLine" in navigator) && !navigator.onLine) {
throw new BrowserOfflineError(error);
}
var serverURL = diagnose.serverURL;
var check;
// If the user gave us a server URL to check whether the server is up at
// all, use it. If that failed, then we need to check the connection. If we
// do not have a server URL, then we need to check the connection right
// away.
if (serverURL) {
// eslint-disable-next-line no-use-before-define
check = ajax({ url: dedupURL(normalizeURL(serverURL)) })
.catch(function failed() {
return connectionCheck(error, diagnose);
});
}
else {
check = connectionCheck(error, diagnose);
}
return check.then(function success() {
// All of our checks passed... and we have no tries left, so just rethrow
// what we would have thrown in the first place.
throw error;
});
} | [
"function",
"diagnoseIt",
"(",
"error",
",",
"diagnose",
")",
"{",
"if",
"(",
"(",
"\"onLine\"",
"in",
"navigator",
")",
"&&",
"!",
"navigator",
".",
"onLine",
")",
"{",
"throw",
"new",
"BrowserOfflineError",
"(",
"error",
")",
";",
"}",
"var",
"serverURL",
"=",
"diagnose",
".",
"serverURL",
";",
"var",
"check",
";",
"if",
"(",
"serverURL",
")",
"{",
"check",
"=",
"ajax",
"(",
"{",
"url",
":",
"dedupURL",
"(",
"normalizeURL",
"(",
"serverURL",
")",
")",
"}",
")",
".",
"catch",
"(",
"function",
"failed",
"(",
")",
"{",
"return",
"connectionCheck",
"(",
"error",
",",
"diagnose",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"check",
"=",
"connectionCheck",
"(",
"error",
",",
"diagnose",
")",
";",
"}",
"return",
"check",
".",
"then",
"(",
"function",
"success",
"(",
")",
"{",
"throw",
"error",
";",
"}",
")",
";",
"}"
] | This is called when our tries all failed. This function attempts to figure out where the issue is. | [
"This",
"is",
"called",
"when",
"our",
"tries",
"all",
"failed",
".",
"This",
"function",
"attempts",
"to",
"figure",
"out",
"where",
"the",
"issue",
"is",
"."
] | 106359491ba707b5bb22b3b5b84cedca08555ff8 | https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L277-L305 | train |
lddubeau/bluejax | index.js | isNetworkIssue | function isNetworkIssue(error) {
// We don't want to retry when a HTTP error occurred.
return !(error instanceof errors.HttpError) &&
!(error instanceof errors.ParserError) &&
!(error instanceof errors.AbortError);
} | javascript | function isNetworkIssue(error) {
// We don't want to retry when a HTTP error occurred.
return !(error instanceof errors.HttpError) &&
!(error instanceof errors.ParserError) &&
!(error instanceof errors.AbortError);
} | [
"function",
"isNetworkIssue",
"(",
"error",
")",
"{",
"return",
"!",
"(",
"error",
"instanceof",
"errors",
".",
"HttpError",
")",
"&&",
"!",
"(",
"error",
"instanceof",
"errors",
".",
"ParserError",
")",
"&&",
"!",
"(",
"error",
"instanceof",
"errors",
".",
"AbortError",
")",
";",
"}"
] | Determine whether the error is due to a network problem. We do not perform diagnosis on errors like an HTTP status code of 400 because errors like these are an indication that the application was not queried properly rather than a problem with the server being inaccessible or a network issue. So we need to distinguish network issues from the rest. | [
"Determine",
"whether",
"the",
"error",
"is",
"due",
"to",
"a",
"network",
"problem",
".",
"We",
"do",
"not",
"perform",
"diagnosis",
"on",
"errors",
"like",
"an",
"HTTP",
"status",
"code",
"of",
"400",
"because",
"errors",
"like",
"these",
"are",
"an",
"indication",
"that",
"the",
"application",
"was",
"not",
"queried",
"properly",
"rather",
"than",
"a",
"problem",
"with",
"the",
"server",
"being",
"inaccessible",
"or",
"a",
"network",
"issue",
".",
"So",
"we",
"need",
"to",
"distinguish",
"network",
"issues",
"from",
"the",
"rest",
"."
] | 106359491ba707b5bb22b3b5b84cedca08555ff8 | https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L312-L317 | train |
lddubeau/bluejax | index.js | doit | function doit(originalArgs, originalSettings, jqOptions, bjOptions) {
var xhr;
var p = new Promise(function resolver(resolve, reject) {
xhr = bluetry.perform.call(this, originalSettings, jqOptions, bjOptions);
function succeded(data, textStatus, jqXHR) {
resolve(bjOptions.verboseResults ? [data, textStatus, jqXHR] : data);
}
function failed(jqXHR, textStatus, errorThrown) {
var error = makeError(
jqXHR, textStatus, errorThrown,
bjOptions.verboseExceptions ? originalArgs : null);
if (!isNetworkIssue(error)) {
// As mentioned earlier, errors that are not due to the network cause
// an immediate rejection: no diagnosis.
reject(error);
}
else {
// Move to perhaps diagnosing what could be the problem.
var diagnose = bjOptions.diagnose;
if (!diagnose || !diagnose.on) {
// The user did not request diagnosis: fail now.
reject(error);
}
else {
// Otherwise, we perform the requested diagnosis. We cannot just
// call ``reject`` with the return value of ``diagnoseIt``, as the
// rejection value would be a promise and not an error. (``resolve``
// assimilates promises, ``reject`` does not).
resolve(diagnoseIt(error, diagnose));
}
}
}
xhr.fail(failed).done(succeded);
});
return { xhr: xhr, promise: p };
} | javascript | function doit(originalArgs, originalSettings, jqOptions, bjOptions) {
var xhr;
var p = new Promise(function resolver(resolve, reject) {
xhr = bluetry.perform.call(this, originalSettings, jqOptions, bjOptions);
function succeded(data, textStatus, jqXHR) {
resolve(bjOptions.verboseResults ? [data, textStatus, jqXHR] : data);
}
function failed(jqXHR, textStatus, errorThrown) {
var error = makeError(
jqXHR, textStatus, errorThrown,
bjOptions.verboseExceptions ? originalArgs : null);
if (!isNetworkIssue(error)) {
// As mentioned earlier, errors that are not due to the network cause
// an immediate rejection: no diagnosis.
reject(error);
}
else {
// Move to perhaps diagnosing what could be the problem.
var diagnose = bjOptions.diagnose;
if (!diagnose || !diagnose.on) {
// The user did not request diagnosis: fail now.
reject(error);
}
else {
// Otherwise, we perform the requested diagnosis. We cannot just
// call ``reject`` with the return value of ``diagnoseIt``, as the
// rejection value would be a promise and not an error. (``resolve``
// assimilates promises, ``reject`` does not).
resolve(diagnoseIt(error, diagnose));
}
}
}
xhr.fail(failed).done(succeded);
});
return { xhr: xhr, promise: p };
} | [
"function",
"doit",
"(",
"originalArgs",
",",
"originalSettings",
",",
"jqOptions",
",",
"bjOptions",
")",
"{",
"var",
"xhr",
";",
"var",
"p",
"=",
"new",
"Promise",
"(",
"function",
"resolver",
"(",
"resolve",
",",
"reject",
")",
"{",
"xhr",
"=",
"bluetry",
".",
"perform",
".",
"call",
"(",
"this",
",",
"originalSettings",
",",
"jqOptions",
",",
"bjOptions",
")",
";",
"function",
"succeded",
"(",
"data",
",",
"textStatus",
",",
"jqXHR",
")",
"{",
"resolve",
"(",
"bjOptions",
".",
"verboseResults",
"?",
"[",
"data",
",",
"textStatus",
",",
"jqXHR",
"]",
":",
"data",
")",
";",
"}",
"function",
"failed",
"(",
"jqXHR",
",",
"textStatus",
",",
"errorThrown",
")",
"{",
"var",
"error",
"=",
"makeError",
"(",
"jqXHR",
",",
"textStatus",
",",
"errorThrown",
",",
"bjOptions",
".",
"verboseExceptions",
"?",
"originalArgs",
":",
"null",
")",
";",
"if",
"(",
"!",
"isNetworkIssue",
"(",
"error",
")",
")",
"{",
"reject",
"(",
"error",
")",
";",
"}",
"else",
"{",
"var",
"diagnose",
"=",
"bjOptions",
".",
"diagnose",
";",
"if",
"(",
"!",
"diagnose",
"||",
"!",
"diagnose",
".",
"on",
")",
"{",
"reject",
"(",
"error",
")",
";",
"}",
"else",
"{",
"resolve",
"(",
"diagnoseIt",
"(",
"error",
",",
"diagnose",
")",
")",
";",
"}",
"}",
"}",
"xhr",
".",
"fail",
"(",
"failed",
")",
".",
"done",
"(",
"succeded",
")",
";",
"}",
")",
";",
"return",
"{",
"xhr",
":",
"xhr",
",",
"promise",
":",
"p",
"}",
";",
"}"
] | This is the core of the functionality provided by Bluejax. | [
"This",
"is",
"the",
"core",
"of",
"the",
"functionality",
"provided",
"by",
"Bluejax",
"."
] | 106359491ba707b5bb22b3b5b84cedca08555ff8 | https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L320-L359 | train |
lddubeau/bluejax | index.js | _ajax$ | function _ajax$(url, settings, override) {
// We just need to split up the arguments and pass them to ``doit``.
var originalArgs = settings ? [url, settings] : [url];
var originalSettings = settings || url;
var extracted = bluetry.extractBluejaxOptions(originalArgs);
// We need a copy here so that we do not mess up what the user passes to us.
var bluejaxOptions = $.extend({}, override, extracted[0]);
var cleanedOptions = extracted[1];
return doit(originalArgs, originalSettings, cleanedOptions, bluejaxOptions);
} | javascript | function _ajax$(url, settings, override) {
// We just need to split up the arguments and pass them to ``doit``.
var originalArgs = settings ? [url, settings] : [url];
var originalSettings = settings || url;
var extracted = bluetry.extractBluejaxOptions(originalArgs);
// We need a copy here so that we do not mess up what the user passes to us.
var bluejaxOptions = $.extend({}, override, extracted[0]);
var cleanedOptions = extracted[1];
return doit(originalArgs, originalSettings, cleanedOptions, bluejaxOptions);
} | [
"function",
"_ajax$",
"(",
"url",
",",
"settings",
",",
"override",
")",
"{",
"var",
"originalArgs",
"=",
"settings",
"?",
"[",
"url",
",",
"settings",
"]",
":",
"[",
"url",
"]",
";",
"var",
"originalSettings",
"=",
"settings",
"||",
"url",
";",
"var",
"extracted",
"=",
"bluetry",
".",
"extractBluejaxOptions",
"(",
"originalArgs",
")",
";",
"var",
"bluejaxOptions",
"=",
"$",
".",
"extend",
"(",
"{",
"}",
",",
"override",
",",
"extracted",
"[",
"0",
"]",
")",
";",
"var",
"cleanedOptions",
"=",
"extracted",
"[",
"1",
"]",
";",
"return",
"doit",
"(",
"originalArgs",
",",
"originalSettings",
",",
"cleanedOptions",
",",
"bluejaxOptions",
")",
";",
"}"
] | We need this so that we can use ``make``. The ``override`` parameter is used solely by ``make`` to pass the options that the user specified on ``make``. | [
"We",
"need",
"this",
"so",
"that",
"we",
"can",
"use",
"make",
".",
"The",
"override",
"parameter",
"is",
"used",
"solely",
"by",
"make",
"to",
"pass",
"the",
"options",
"that",
"the",
"user",
"specified",
"on",
"make",
"."
] | 106359491ba707b5bb22b3b5b84cedca08555ff8 | https://github.com/lddubeau/bluejax/blob/106359491ba707b5bb22b3b5b84cedca08555ff8/index.js#L364-L373 | train |
mwittig/logger-winston | logger-winston.js | init | function init(config) {
// the given config is only applied if no config has been set already (stored as localConfig)
if (Object.keys(localConfig).length === 0) {
if (config.hasOwnProperty("logging") && (config.logging.constructor === {}.constructor)) {
// config has "logging" key with an {} object value
//console.log("LOGGER: Setting config");
localConfig = _merge({}, config.logging);
}
else {
// no valid config - use default
localConfig = { default: { console: {}}};
}
}
} | javascript | function init(config) {
// the given config is only applied if no config has been set already (stored as localConfig)
if (Object.keys(localConfig).length === 0) {
if (config.hasOwnProperty("logging") && (config.logging.constructor === {}.constructor)) {
// config has "logging" key with an {} object value
//console.log("LOGGER: Setting config");
localConfig = _merge({}, config.logging);
}
else {
// no valid config - use default
localConfig = { default: { console: {}}};
}
}
} | [
"function",
"init",
"(",
"config",
")",
"{",
"if",
"(",
"Object",
".",
"keys",
"(",
"localConfig",
")",
".",
"length",
"===",
"0",
")",
"{",
"if",
"(",
"config",
".",
"hasOwnProperty",
"(",
"\"logging\"",
")",
"&&",
"(",
"config",
".",
"logging",
".",
"constructor",
"===",
"{",
"}",
".",
"constructor",
")",
")",
"{",
"localConfig",
"=",
"_merge",
"(",
"{",
"}",
",",
"config",
".",
"logging",
")",
";",
"}",
"else",
"{",
"localConfig",
"=",
"{",
"default",
":",
"{",
"console",
":",
"{",
"}",
"}",
"}",
";",
"}",
"}",
"}"
] | Initialize logging with the given configuration. As the given configuration will be cached internally the first
invocation will take effect, only. Make sure to invoke this function at the very beginning of the program before
other topics using logging get loaded.
@param {Object} config - The logging configuration.
@param {Object} config.logging - Contains the logging configuration for at least one winston container. A specific
container configuration can be provided by defining a configuration for a category matching the topicName. A
default configuration can provided by defining a container for the category "default". A container configuration
contains at least one transport configuration.
Note, you may run into an issue in strict mode, if you need to setup multiple transports of the same type, e.g.,
two file transports, as the strict mode inhibits duplicate object keys. In this case the transport name can be
augmented with a "#name" postfix, e.g. "file#debug".
@param {Object} [config.logging.[topicName]=default] - A specific container for a given topicName can be setup by
providing a container configuration where the property name is equal to given topicName. The container configuration
must contain at least one winston transport configuration. If the container configuration contains the key
"inheritDefault" set to true, the default configuration will be mixed in. This way, it possible to solely define
transport properties which shall differ from the default configuration.
@param {Object} [config.logging.default=builtin] - Contains the default configuration applicable to loggers without a
specific container configuration. The container configuration must contain at least one winston transport
configuration. If no default configuration is provided a console transport configuration with
winston builtin defaults will be used. | [
"Initialize",
"logging",
"with",
"the",
"given",
"configuration",
".",
"As",
"the",
"given",
"configuration",
"will",
"be",
"cached",
"internally",
"the",
"first",
"invocation",
"will",
"take",
"effect",
"only",
".",
"Make",
"sure",
"to",
"invoke",
"this",
"function",
"at",
"the",
"very",
"beginning",
"of",
"the",
"program",
"before",
"other",
"topics",
"using",
"logging",
"get",
"loaded",
"."
] | 0893c8714d78bdf33294b300f6c9cddf4ccef9f5 | https://github.com/mwittig/logger-winston/blob/0893c8714d78bdf33294b300f6c9cddf4ccef9f5/logger-winston.js#L31-L44 | train |
mallocator/gulp-international | index.js | trueOrMatch | function trueOrMatch(needle, haystack) {
if (needle === true) {
return true;
}
if (_.isRegExp(needle) && needle.test(haystack)) {
return true;
}
if (_.isString(needle) && haystack.indexOf(needle) !== -1) {
return true;
}
if (needle instanceof Array) {
for (var i in needle) {
if (trueOrMatch(needle[i], haystack)) {
return true;
}
}
}
return false;
} | javascript | function trueOrMatch(needle, haystack) {
if (needle === true) {
return true;
}
if (_.isRegExp(needle) && needle.test(haystack)) {
return true;
}
if (_.isString(needle) && haystack.indexOf(needle) !== -1) {
return true;
}
if (needle instanceof Array) {
for (var i in needle) {
if (trueOrMatch(needle[i], haystack)) {
return true;
}
}
}
return false;
} | [
"function",
"trueOrMatch",
"(",
"needle",
",",
"haystack",
")",
"{",
"if",
"(",
"needle",
"===",
"true",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"_",
".",
"isRegExp",
"(",
"needle",
")",
"&&",
"needle",
".",
"test",
"(",
"haystack",
")",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"_",
".",
"isString",
"(",
"needle",
")",
"&&",
"haystack",
".",
"indexOf",
"(",
"needle",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"true",
";",
"}",
"if",
"(",
"needle",
"instanceof",
"Array",
")",
"{",
"for",
"(",
"var",
"i",
"in",
"needle",
")",
"{",
"if",
"(",
"trueOrMatch",
"(",
"needle",
"[",
"i",
"]",
",",
"haystack",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
] | A helper function to test whether an option was set to true or the value matches the options regular expression.
@param {boolean|string|RegExp} needle
@param {String} haystack
@returns {boolean} | [
"A",
"helper",
"function",
"to",
"test",
"whether",
"an",
"option",
"was",
"set",
"to",
"true",
"or",
"the",
"value",
"matches",
"the",
"options",
"regular",
"expression",
"."
] | 0b235341acd1d72937e900f13fd4a6de855ff1e4 | https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L54-L72 | train |
mallocator/gulp-international | index.js | splitIniLine | function splitIniLine(line) {
var separator = line.indexOf('=');
if (separator === -1) {
return [line];
}
return [
line.substr(0, separator),
line.substr(separator + 1)
];
} | javascript | function splitIniLine(line) {
var separator = line.indexOf('=');
if (separator === -1) {
return [line];
}
return [
line.substr(0, separator),
line.substr(separator + 1)
];
} | [
"function",
"splitIniLine",
"(",
"line",
")",
"{",
"var",
"separator",
"=",
"line",
".",
"indexOf",
"(",
"'='",
")",
";",
"if",
"(",
"separator",
"===",
"-",
"1",
")",
"{",
"return",
"[",
"line",
"]",
";",
"}",
"return",
"[",
"line",
".",
"substr",
"(",
"0",
",",
"separator",
")",
",",
"line",
".",
"substr",
"(",
"separator",
"+",
"1",
")",
"]",
";",
"}"
] | Splits a line from an ini file into 2. Any subsequent '=' are ignored.
@param {String} line
@returns {String[]} | [
"Splits",
"a",
"line",
"from",
"an",
"ini",
"file",
"into",
"2",
".",
"Any",
"subsequent",
"=",
"are",
"ignored",
"."
] | 0b235341acd1d72937e900f13fd4a6de855ff1e4 | https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L79-L88 | train |
mallocator/gulp-international | index.js | ini2json | function ini2json(iniData) {
var result = {};
var iniLines = iniData.toString().split('\n');
var context = null;
for (var i in iniLines) {
var fields = splitIniLine(iniLines[i]);
for (var j in fields) {
fields[j] = fields[j].trim();
}
if (fields[0].length) {
if (fields[0].indexOf('[')===0) {
context = fields[0].substring(1, fields[0].length - 1);
} else {
if (context) {
if (!result[context]) {
result[context] = {};
}
result[context][fields[0]] = fields[1];
} else {
result[fields[0]] = fields[1];
}
}
}
}
return result;
} | javascript | function ini2json(iniData) {
var result = {};
var iniLines = iniData.toString().split('\n');
var context = null;
for (var i in iniLines) {
var fields = splitIniLine(iniLines[i]);
for (var j in fields) {
fields[j] = fields[j].trim();
}
if (fields[0].length) {
if (fields[0].indexOf('[')===0) {
context = fields[0].substring(1, fields[0].length - 1);
} else {
if (context) {
if (!result[context]) {
result[context] = {};
}
result[context][fields[0]] = fields[1];
} else {
result[fields[0]] = fields[1];
}
}
}
}
return result;
} | [
"function",
"ini2json",
"(",
"iniData",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"var",
"iniLines",
"=",
"iniData",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
";",
"\\n",
"var",
"context",
"=",
"null",
";",
"for",
"(",
"var",
"i",
"in",
"iniLines",
")",
"{",
"var",
"fields",
"=",
"splitIniLine",
"(",
"iniLines",
"[",
"i",
"]",
")",
";",
"for",
"(",
"var",
"j",
"in",
"fields",
")",
"{",
"fields",
"[",
"j",
"]",
"=",
"fields",
"[",
"j",
"]",
".",
"trim",
"(",
")",
";",
"}",
"if",
"(",
"fields",
"[",
"0",
"]",
".",
"length",
")",
"{",
"if",
"(",
"fields",
"[",
"0",
"]",
".",
"indexOf",
"(",
"'['",
")",
"===",
"0",
")",
"{",
"context",
"=",
"fields",
"[",
"0",
"]",
".",
"substring",
"(",
"1",
",",
"fields",
"[",
"0",
"]",
".",
"length",
"-",
"1",
")",
";",
"}",
"else",
"{",
"if",
"(",
"context",
")",
"{",
"if",
"(",
"!",
"result",
"[",
"context",
"]",
")",
"{",
"result",
"[",
"context",
"]",
"=",
"{",
"}",
";",
"}",
"result",
"[",
"context",
"]",
"[",
"fields",
"[",
"0",
"]",
"]",
"=",
"fields",
"[",
"1",
"]",
";",
"}",
"else",
"{",
"result",
"[",
"fields",
"[",
"0",
"]",
"]",
"=",
"fields",
"[",
"1",
"]",
";",
"}",
"}",
"}",
"}",
"}"
] | Simple conversion helper to get a json file from an ini file.
@param {String} iniData
@returns {{}} | [
"Simple",
"conversion",
"helper",
"to",
"get",
"a",
"json",
"file",
"from",
"an",
"ini",
"file",
"."
] | 0b235341acd1d72937e900f13fd4a6de855ff1e4 | https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L95-L120 | train |
mallocator/gulp-international | index.js | splitCsvLine | function splitCsvLine(line) {
if (!line.trim().length) {
return [];
}
var fields = [];
var inQuotes = false;
var separator = 0;
for (var i = 0; i < line.length; i++) {
switch(line[i]) {
case "\"":
if (i>0 && line[i-1] != "\\") {
inQuotes = !inQuotes;
}
break;
case ",":
if (!inQuotes) {
if (separator < i) {
var field = line.substring(separator, i).trim();
if (field.length) {
fields.push(field);
}
}
separator = i + 1;
}
break;
}
}
fields.push(line.substring(separator).trim());
return fields;
} | javascript | function splitCsvLine(line) {
if (!line.trim().length) {
return [];
}
var fields = [];
var inQuotes = false;
var separator = 0;
for (var i = 0; i < line.length; i++) {
switch(line[i]) {
case "\"":
if (i>0 && line[i-1] != "\\") {
inQuotes = !inQuotes;
}
break;
case ",":
if (!inQuotes) {
if (separator < i) {
var field = line.substring(separator, i).trim();
if (field.length) {
fields.push(field);
}
}
separator = i + 1;
}
break;
}
}
fields.push(line.substring(separator).trim());
return fields;
} | [
"function",
"splitCsvLine",
"(",
"line",
")",
"{",
"if",
"(",
"!",
"line",
".",
"trim",
"(",
")",
".",
"length",
")",
"{",
"return",
"[",
"]",
";",
"}",
"var",
"fields",
"=",
"[",
"]",
";",
"var",
"inQuotes",
"=",
"false",
";",
"var",
"separator",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"line",
".",
"length",
";",
"i",
"++",
")",
"{",
"switch",
"(",
"line",
"[",
"i",
"]",
")",
"{",
"case",
"\"\\\"\"",
":",
"\\\"",
"if",
"(",
"i",
">",
"0",
"&&",
"line",
"[",
"i",
"-",
"1",
"]",
"!=",
"\"\\\\\"",
")",
"\\\\",
"{",
"inQuotes",
"=",
"!",
"inQuotes",
";",
"}",
"}",
"}",
"break",
";",
"case",
"\",\"",
":",
"if",
"(",
"!",
"inQuotes",
")",
"{",
"if",
"(",
"separator",
"<",
"i",
")",
"{",
"var",
"field",
"=",
"line",
".",
"substring",
"(",
"separator",
",",
"i",
")",
".",
"trim",
"(",
")",
";",
"if",
"(",
"field",
".",
"length",
")",
"{",
"fields",
".",
"push",
"(",
"field",
")",
";",
"}",
"}",
"separator",
"=",
"i",
"+",
"1",
";",
"}",
"break",
";",
"}"
] | Converts a line of a CSV file to an array of strings, omitting empty fields.
@param {String} line
@returns {String[]} | [
"Converts",
"a",
"line",
"of",
"a",
"CSV",
"file",
"to",
"an",
"array",
"of",
"strings",
"omitting",
"empty",
"fields",
"."
] | 0b235341acd1d72937e900f13fd4a6de855ff1e4 | https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L127-L156 | train |
mallocator/gulp-international | index.js | csv2json | function csv2json(csvData) {
var result = {};
var csvLines = csvData.toString().split('\n');
for (var i in csvLines) {
var fields = splitCsvLine(csvLines[i]);
if (fields.length) {
var key = '';
for (var k = 0; k < fields.length - 1; k++) {
if (fields[k].length) {
key += '.' + fields[k];
}
}
result[key.substr(1)] = fields[fields.length - 1];
}
}
return result;
} | javascript | function csv2json(csvData) {
var result = {};
var csvLines = csvData.toString().split('\n');
for (var i in csvLines) {
var fields = splitCsvLine(csvLines[i]);
if (fields.length) {
var key = '';
for (var k = 0; k < fields.length - 1; k++) {
if (fields[k].length) {
key += '.' + fields[k];
}
}
result[key.substr(1)] = fields[fields.length - 1];
}
}
return result;
} | [
"function",
"csv2json",
"(",
"csvData",
")",
"{",
"var",
"result",
"=",
"{",
"}",
";",
"var",
"csvLines",
"=",
"csvData",
".",
"toString",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
";",
"\\n",
"for",
"(",
"var",
"i",
"in",
"csvLines",
")",
"{",
"var",
"fields",
"=",
"splitCsvLine",
"(",
"csvLines",
"[",
"i",
"]",
")",
";",
"if",
"(",
"fields",
".",
"length",
")",
"{",
"var",
"key",
"=",
"''",
";",
"for",
"(",
"var",
"k",
"=",
"0",
";",
"k",
"<",
"fields",
".",
"length",
"-",
"1",
";",
"k",
"++",
")",
"{",
"if",
"(",
"fields",
"[",
"k",
"]",
".",
"length",
")",
"{",
"key",
"+=",
"'.'",
"+",
"fields",
"[",
"k",
"]",
";",
"}",
"}",
"result",
"[",
"key",
".",
"substr",
"(",
"1",
")",
"]",
"=",
"fields",
"[",
"fields",
".",
"length",
"-",
"1",
"]",
";",
"}",
"}",
"}"
] | Simple conversion helper to get a json file from a csv file.
@param {String} csvData
@returns {Object} | [
"Simple",
"conversion",
"helper",
"to",
"get",
"a",
"json",
"file",
"from",
"a",
"csv",
"file",
"."
] | 0b235341acd1d72937e900f13fd4a6de855ff1e4 | https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L163-L179 | train |
mallocator/gulp-international | index.js | load | function load(options) {
if (cache[options.locales]) {
options.verbose && gutil.log('Skip loading cached translations from', options.locales);
return dictionaries = cache[options.locales];
}
try {
options.verbose && gutil.log('Loading translations from', options.locales);
var files = fs.readdirSync(options.locales);
var count = 0;
for (var i in files) {
var file = files[i];
switch (path.extname(file)) {
case '.json':
case '.js':
dictionaries[path.basename(file, path.extname(file))] = flat(require(path.join(process.cwd(), options.locales, file)));
options.verbose && gutil.log('Added translations from', file);
count++;
break;
case '.ini':
var iniData = fs.readFileSync(path.join(process.cwd(), options.locales, file));
dictionaries[path.basename(file, path.extname(file))] = flat(ini2json(iniData));
options.verbose && gutil.log('Added translations from', file);
count++;
break;
case '.csv':
var csvData = fs.readFileSync(path.join(process.cwd(), options.locales, file));
dictionaries[path.basename(file, path.extname(file))] = csv2json(csvData);
options.verbose && gutil.log('Added translations from', file);
count++;
break;
default:
options.verbose && gutil.log('Ignored file', file);
}
}
options.verbose && gutil.log('Loaded', count, 'translations from', options.locales);
if (options.cache) {
options.verbose && gutil.log('Cashing translations from', options.locales);
cache[options.locales] = dictionaries;
}
} catch (e) {
e.message = 'No translation dictionaries have been found!';
throw e;
}
} | javascript | function load(options) {
if (cache[options.locales]) {
options.verbose && gutil.log('Skip loading cached translations from', options.locales);
return dictionaries = cache[options.locales];
}
try {
options.verbose && gutil.log('Loading translations from', options.locales);
var files = fs.readdirSync(options.locales);
var count = 0;
for (var i in files) {
var file = files[i];
switch (path.extname(file)) {
case '.json':
case '.js':
dictionaries[path.basename(file, path.extname(file))] = flat(require(path.join(process.cwd(), options.locales, file)));
options.verbose && gutil.log('Added translations from', file);
count++;
break;
case '.ini':
var iniData = fs.readFileSync(path.join(process.cwd(), options.locales, file));
dictionaries[path.basename(file, path.extname(file))] = flat(ini2json(iniData));
options.verbose && gutil.log('Added translations from', file);
count++;
break;
case '.csv':
var csvData = fs.readFileSync(path.join(process.cwd(), options.locales, file));
dictionaries[path.basename(file, path.extname(file))] = csv2json(csvData);
options.verbose && gutil.log('Added translations from', file);
count++;
break;
default:
options.verbose && gutil.log('Ignored file', file);
}
}
options.verbose && gutil.log('Loaded', count, 'translations from', options.locales);
if (options.cache) {
options.verbose && gutil.log('Cashing translations from', options.locales);
cache[options.locales] = dictionaries;
}
} catch (e) {
e.message = 'No translation dictionaries have been found!';
throw e;
}
} | [
"function",
"load",
"(",
"options",
")",
"{",
"if",
"(",
"cache",
"[",
"options",
".",
"locales",
"]",
")",
"{",
"options",
".",
"verbose",
"&&",
"gutil",
".",
"log",
"(",
"'Skip loading cached translations from'",
",",
"options",
".",
"locales",
")",
";",
"return",
"dictionaries",
"=",
"cache",
"[",
"options",
".",
"locales",
"]",
";",
"}",
"try",
"{",
"options",
".",
"verbose",
"&&",
"gutil",
".",
"log",
"(",
"'Loading translations from'",
",",
"options",
".",
"locales",
")",
";",
"var",
"files",
"=",
"fs",
".",
"readdirSync",
"(",
"options",
".",
"locales",
")",
";",
"var",
"count",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"in",
"files",
")",
"{",
"var",
"file",
"=",
"files",
"[",
"i",
"]",
";",
"switch",
"(",
"path",
".",
"extname",
"(",
"file",
")",
")",
"{",
"case",
"'.json'",
":",
"case",
"'.js'",
":",
"dictionaries",
"[",
"path",
".",
"basename",
"(",
"file",
",",
"path",
".",
"extname",
"(",
"file",
")",
")",
"]",
"=",
"flat",
"(",
"require",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"options",
".",
"locales",
",",
"file",
")",
")",
")",
";",
"options",
".",
"verbose",
"&&",
"gutil",
".",
"log",
"(",
"'Added translations from'",
",",
"file",
")",
";",
"count",
"++",
";",
"break",
";",
"case",
"'.ini'",
":",
"var",
"iniData",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"options",
".",
"locales",
",",
"file",
")",
")",
";",
"dictionaries",
"[",
"path",
".",
"basename",
"(",
"file",
",",
"path",
".",
"extname",
"(",
"file",
")",
")",
"]",
"=",
"flat",
"(",
"ini2json",
"(",
"iniData",
")",
")",
";",
"options",
".",
"verbose",
"&&",
"gutil",
".",
"log",
"(",
"'Added translations from'",
",",
"file",
")",
";",
"count",
"++",
";",
"break",
";",
"case",
"'.csv'",
":",
"var",
"csvData",
"=",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"process",
".",
"cwd",
"(",
")",
",",
"options",
".",
"locales",
",",
"file",
")",
")",
";",
"dictionaries",
"[",
"path",
".",
"basename",
"(",
"file",
",",
"path",
".",
"extname",
"(",
"file",
")",
")",
"]",
"=",
"csv2json",
"(",
"csvData",
")",
";",
"options",
".",
"verbose",
"&&",
"gutil",
".",
"log",
"(",
"'Added translations from'",
",",
"file",
")",
";",
"count",
"++",
";",
"break",
";",
"default",
":",
"options",
".",
"verbose",
"&&",
"gutil",
".",
"log",
"(",
"'Ignored file'",
",",
"file",
")",
";",
"}",
"}",
"options",
".",
"verbose",
"&&",
"gutil",
".",
"log",
"(",
"'Loaded'",
",",
"count",
",",
"'translations from'",
",",
"options",
".",
"locales",
")",
";",
"if",
"(",
"options",
".",
"cache",
")",
"{",
"options",
".",
"verbose",
"&&",
"gutil",
".",
"log",
"(",
"'Cashing translations from'",
",",
"options",
".",
"locales",
")",
";",
"cache",
"[",
"options",
".",
"locales",
"]",
"=",
"dictionaries",
";",
"}",
"}",
"catch",
"(",
"e",
")",
"{",
"e",
".",
"message",
"=",
"'No translation dictionaries have been found!'",
";",
"throw",
"e",
";",
"}",
"}"
] | Loads the dictionaries from the locale directory.
@param {Object} options | [
"Loads",
"the",
"dictionaries",
"from",
"the",
"locale",
"directory",
"."
] | 0b235341acd1d72937e900f13fd4a6de855ff1e4 | https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L185-L228 | train |
mallocator/gulp-international | index.js | isBinary | function isBinary(buffer) {
var chunk = buffer.toString('utf8', 0, Math.min(buffer.length, 24));
for (var i in chunk) {
var charCode = chunk.charCodeAt(i);
if (charCode == 65533 || charCode <= 8) {
return true;
}
}
return false;
} | javascript | function isBinary(buffer) {
var chunk = buffer.toString('utf8', 0, Math.min(buffer.length, 24));
for (var i in chunk) {
var charCode = chunk.charCodeAt(i);
if (charCode == 65533 || charCode <= 8) {
return true;
}
}
return false;
} | [
"function",
"isBinary",
"(",
"buffer",
")",
"{",
"var",
"chunk",
"=",
"buffer",
".",
"toString",
"(",
"'utf8'",
",",
"0",
",",
"Math",
".",
"min",
"(",
"buffer",
".",
"length",
",",
"24",
")",
")",
";",
"for",
"(",
"var",
"i",
"in",
"chunk",
")",
"{",
"var",
"charCode",
"=",
"chunk",
".",
"charCodeAt",
"(",
"i",
")",
";",
"if",
"(",
"charCode",
"==",
"65533",
"||",
"charCode",
"<=",
"8",
")",
"{",
"return",
"true",
";",
"}",
"}",
"return",
"false",
";",
"}"
] | Helper function that detects whether a buffer is binary or utf8.
@param {Buffer} buffer
@returns {boolean} | [
"Helper",
"function",
"that",
"detects",
"whether",
"a",
"buffer",
"is",
"binary",
"or",
"utf8",
"."
] | 0b235341acd1d72937e900f13fd4a6de855ff1e4 | https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L235-L244 | train |
mallocator/gulp-international | index.js | replace | function replace(file, options) {
var contents = file.contents;
var copied = 0;
var processed = translate(options, contents, copied, file.path);
var files = [];
for (var lang in processed) {
var params = {};
params.ext = path.extname(file.path).substr(1);
params.name = path.basename(file.path, path.extname(file.path));
params.path = file.path.substring(file.base.length, file.path.lastIndexOf(path.sep));
params.lang = lang;
var filePath = options.filename;
for (var param in params) {
filePath = filePath.replace('${' + param + '}', params[param]);
}
filePath = path.join(file.base,filePath);
var newFile = new gutil.File({
base: file.base,
cwd: file.cwd,
path: filePath,
contents: new Buffer(processed[lang], 'utf8')
});
files.push(newFile);
}
return files;
} | javascript | function replace(file, options) {
var contents = file.contents;
var copied = 0;
var processed = translate(options, contents, copied, file.path);
var files = [];
for (var lang in processed) {
var params = {};
params.ext = path.extname(file.path).substr(1);
params.name = path.basename(file.path, path.extname(file.path));
params.path = file.path.substring(file.base.length, file.path.lastIndexOf(path.sep));
params.lang = lang;
var filePath = options.filename;
for (var param in params) {
filePath = filePath.replace('${' + param + '}', params[param]);
}
filePath = path.join(file.base,filePath);
var newFile = new gutil.File({
base: file.base,
cwd: file.cwd,
path: filePath,
contents: new Buffer(processed[lang], 'utf8')
});
files.push(newFile);
}
return files;
} | [
"function",
"replace",
"(",
"file",
",",
"options",
")",
"{",
"var",
"contents",
"=",
"file",
".",
"contents",
";",
"var",
"copied",
"=",
"0",
";",
"var",
"processed",
"=",
"translate",
"(",
"options",
",",
"contents",
",",
"copied",
",",
"file",
".",
"path",
")",
";",
"var",
"files",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"lang",
"in",
"processed",
")",
"{",
"var",
"params",
"=",
"{",
"}",
";",
"params",
".",
"ext",
"=",
"path",
".",
"extname",
"(",
"file",
".",
"path",
")",
".",
"substr",
"(",
"1",
")",
";",
"params",
".",
"name",
"=",
"path",
".",
"basename",
"(",
"file",
".",
"path",
",",
"path",
".",
"extname",
"(",
"file",
".",
"path",
")",
")",
";",
"params",
".",
"path",
"=",
"file",
".",
"path",
".",
"substring",
"(",
"file",
".",
"base",
".",
"length",
",",
"file",
".",
"path",
".",
"lastIndexOf",
"(",
"path",
".",
"sep",
")",
")",
";",
"params",
".",
"lang",
"=",
"lang",
";",
"var",
"filePath",
"=",
"options",
".",
"filename",
";",
"for",
"(",
"var",
"param",
"in",
"params",
")",
"{",
"filePath",
"=",
"filePath",
".",
"replace",
"(",
"'${'",
"+",
"param",
"+",
"'}'",
",",
"params",
"[",
"param",
"]",
")",
";",
"}",
"filePath",
"=",
"path",
".",
"join",
"(",
"file",
".",
"base",
",",
"filePath",
")",
";",
"var",
"newFile",
"=",
"new",
"gutil",
".",
"File",
"(",
"{",
"base",
":",
"file",
".",
"base",
",",
"cwd",
":",
"file",
".",
"cwd",
",",
"path",
":",
"filePath",
",",
"contents",
":",
"new",
"Buffer",
"(",
"processed",
"[",
"lang",
"]",
",",
"'utf8'",
")",
"}",
")",
";",
"files",
".",
"push",
"(",
"newFile",
")",
";",
"}",
"return",
"files",
";",
"}"
] | Performs the actual replacing of tokens with translations.
@param {File} file
@param {Object} options
@returns {File[]} | [
"Performs",
"the",
"actual",
"replacing",
"of",
"tokens",
"with",
"translations",
"."
] | 0b235341acd1d72937e900f13fd4a6de855ff1e4 | https://github.com/mallocator/gulp-international/blob/0b235341acd1d72937e900f13fd4a6de855ff1e4/index.js#L321-L351 | train |
mesqueeb/find-and-replace-anything | dist/index.esm.js | findAndReplace | function findAndReplace(target, find, replaceWith, config) {
if (config === void 0) { config = { onlyPlainObjects: false }; }
if ((config.onlyPlainObjects === false && !isAnyObject(target)) ||
(config.onlyPlainObjects === true && !isPlainObject(target))) {
if (target === find)
return replaceWith;
return target;
}
return Object.keys(target)
.reduce(function (carry, key) {
var val = target[key];
carry[key] = findAndReplace(val, find, replaceWith, config);
return carry;
}, {});
} | javascript | function findAndReplace(target, find, replaceWith, config) {
if (config === void 0) { config = { onlyPlainObjects: false }; }
if ((config.onlyPlainObjects === false && !isAnyObject(target)) ||
(config.onlyPlainObjects === true && !isPlainObject(target))) {
if (target === find)
return replaceWith;
return target;
}
return Object.keys(target)
.reduce(function (carry, key) {
var val = target[key];
carry[key] = findAndReplace(val, find, replaceWith, config);
return carry;
}, {});
} | [
"function",
"findAndReplace",
"(",
"target",
",",
"find",
",",
"replaceWith",
",",
"config",
")",
"{",
"if",
"(",
"config",
"===",
"void",
"0",
")",
"{",
"config",
"=",
"{",
"onlyPlainObjects",
":",
"false",
"}",
";",
"}",
"if",
"(",
"(",
"config",
".",
"onlyPlainObjects",
"===",
"false",
"&&",
"!",
"isAnyObject",
"(",
"target",
")",
")",
"||",
"(",
"config",
".",
"onlyPlainObjects",
"===",
"true",
"&&",
"!",
"isPlainObject",
"(",
"target",
")",
")",
")",
"{",
"if",
"(",
"target",
"===",
"find",
")",
"return",
"replaceWith",
";",
"return",
"target",
";",
"}",
"return",
"Object",
".",
"keys",
"(",
"target",
")",
".",
"reduce",
"(",
"function",
"(",
"carry",
",",
"key",
")",
"{",
"var",
"val",
"=",
"target",
"[",
"key",
"]",
";",
"carry",
"[",
"key",
"]",
"=",
"findAndReplace",
"(",
"val",
",",
"find",
",",
"replaceWith",
",",
"config",
")",
";",
"return",
"carry",
";",
"}",
",",
"{",
"}",
")",
";",
"}"
] | Goes through an object recursively and replaces all occurences of the `find` value with `replaceWith`. Also works no non-objects.
@export
@param {*} target Target can be anything
@param {*} find val to find
@param {*} replaceWith val to replace
@param {IConfig} [config={onlyPlainObjects: false}]
@returns {*} the target with replaced values | [
"Goes",
"through",
"an",
"object",
"recursively",
"and",
"replaces",
"all",
"occurences",
"of",
"the",
"find",
"value",
"with",
"replaceWith",
".",
"Also",
"works",
"no",
"non",
"-",
"objects",
"."
] | 67ea731c5d39a222a804abc637d26061a3076001 | https://github.com/mesqueeb/find-and-replace-anything/blob/67ea731c5d39a222a804abc637d26061a3076001/dist/index.esm.js#L13-L27 | train |
mesqueeb/find-and-replace-anything | dist/index.esm.js | findAndReplaceIf | function findAndReplaceIf(target, checkFn) {
if (!isPlainObject(target))
return checkFn(target);
return Object.keys(target)
.reduce(function (carry, key) {
var val = target[key];
carry[key] = findAndReplaceIf(val, checkFn);
return carry;
}, {});
} | javascript | function findAndReplaceIf(target, checkFn) {
if (!isPlainObject(target))
return checkFn(target);
return Object.keys(target)
.reduce(function (carry, key) {
var val = target[key];
carry[key] = findAndReplaceIf(val, checkFn);
return carry;
}, {});
} | [
"function",
"findAndReplaceIf",
"(",
"target",
",",
"checkFn",
")",
"{",
"if",
"(",
"!",
"isPlainObject",
"(",
"target",
")",
")",
"return",
"checkFn",
"(",
"target",
")",
";",
"return",
"Object",
".",
"keys",
"(",
"target",
")",
".",
"reduce",
"(",
"function",
"(",
"carry",
",",
"key",
")",
"{",
"var",
"val",
"=",
"target",
"[",
"key",
"]",
";",
"carry",
"[",
"key",
"]",
"=",
"findAndReplaceIf",
"(",
"val",
",",
"checkFn",
")",
";",
"return",
"carry",
";",
"}",
",",
"{",
"}",
")",
";",
"}"
] | Goes through an object recursively and replaces all props with what's is returned in the `checkFn`. Also works no non-objects.
@export
@param {*} target Target can be anything
@param {*} checkFn a function that will receive the `foundVal`
@returns {*} the target with replaced values | [
"Goes",
"through",
"an",
"object",
"recursively",
"and",
"replaces",
"all",
"props",
"with",
"what",
"s",
"is",
"returned",
"in",
"the",
"checkFn",
".",
"Also",
"works",
"no",
"non",
"-",
"objects",
"."
] | 67ea731c5d39a222a804abc637d26061a3076001 | https://github.com/mesqueeb/find-and-replace-anything/blob/67ea731c5d39a222a804abc637d26061a3076001/dist/index.esm.js#L36-L45 | train |
ProperJS/hobo | lib/core/on.js | function ( e ) {
// Default context is `this` element
var context = (selector ? matchElement( e.target, selector, true ) : this);
// Handle `mouseenter` and `mouseleave`
if ( event === "mouseenter" || event === "mouseleave" ) {
var relatedElement = (event === "mouseenter" ? e.fromElement : e.toElement);
if ( context && ( relatedElement !== context && !context.contains( relatedElement ) ) ) {
callback.call( context, e );
}
// Fire callback if context element
} else if ( context ) {
callback.call( context, e );
}
} | javascript | function ( e ) {
// Default context is `this` element
var context = (selector ? matchElement( e.target, selector, true ) : this);
// Handle `mouseenter` and `mouseleave`
if ( event === "mouseenter" || event === "mouseleave" ) {
var relatedElement = (event === "mouseenter" ? e.fromElement : e.toElement);
if ( context && ( relatedElement !== context && !context.contains( relatedElement ) ) ) {
callback.call( context, e );
}
// Fire callback if context element
} else if ( context ) {
callback.call( context, e );
}
} | [
"function",
"(",
"e",
")",
"{",
"var",
"context",
"=",
"(",
"selector",
"?",
"matchElement",
"(",
"e",
".",
"target",
",",
"selector",
",",
"true",
")",
":",
"this",
")",
";",
"if",
"(",
"event",
"===",
"\"mouseenter\"",
"||",
"event",
"===",
"\"mouseleave\"",
")",
"{",
"var",
"relatedElement",
"=",
"(",
"event",
"===",
"\"mouseenter\"",
"?",
"e",
".",
"fromElement",
":",
"e",
".",
"toElement",
")",
";",
"if",
"(",
"context",
"&&",
"(",
"relatedElement",
"!==",
"context",
"&&",
"!",
"context",
".",
"contains",
"(",
"relatedElement",
")",
")",
")",
"{",
"callback",
".",
"call",
"(",
"context",
",",
"e",
")",
";",
"}",
"}",
"else",
"if",
"(",
"context",
")",
"{",
"callback",
".",
"call",
"(",
"context",
",",
"e",
")",
";",
"}",
"}"
] | Unique ID for each node event | [
"Unique",
"ID",
"for",
"each",
"node",
"event"
] | 505caadb3d66ba8257c188acb77645b335f66760 | https://github.com/ProperJS/hobo/blob/505caadb3d66ba8257c188acb77645b335f66760/lib/core/on.js#L25-L41 | train |
|
tadam313/sheet-db | src/query.js | binaryOperator | function binaryOperator(queryObject, actualField, key) {
return actualField + OPS[key] + stringify(queryObject, actualField);
} | javascript | function binaryOperator(queryObject, actualField, key) {
return actualField + OPS[key] + stringify(queryObject, actualField);
} | [
"function",
"binaryOperator",
"(",
"queryObject",
",",
"actualField",
",",
"key",
")",
"{",
"return",
"actualField",
"+",
"OPS",
"[",
"key",
"]",
"+",
"stringify",
"(",
"queryObject",
",",
"actualField",
")",
";",
"}"
] | Converts binary operator queries into string by applying operator and
recursively invokes parsing process for rvalue.
@param {object} queryObject Which contains the operator.
@param {string} actualField Current field of the object which the filter is operating on.
@param {string} key The current operation key.
@returns {string} | [
"Converts",
"binary",
"operator",
"queries",
"into",
"string",
"by",
"applying",
"operator",
"and",
"recursively",
"invokes",
"parsing",
"process",
"for",
"rvalue",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/query.js#L84-L86 | train |
tadam313/sheet-db | src/query.js | logicalOperator | function logicalOperator(queryObject, actualField, key) {
let textQuery = '(';
for (let i = 0; i < queryObject.length; i++) {
textQuery += (i > 0 ? OPS[key] : '') + stringify(queryObject[i], actualField);
}
return textQuery + ')';
} | javascript | function logicalOperator(queryObject, actualField, key) {
let textQuery = '(';
for (let i = 0; i < queryObject.length; i++) {
textQuery += (i > 0 ? OPS[key] : '') + stringify(queryObject[i], actualField);
}
return textQuery + ')';
} | [
"function",
"logicalOperator",
"(",
"queryObject",
",",
"actualField",
",",
"key",
")",
"{",
"let",
"textQuery",
"=",
"'('",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"queryObject",
".",
"length",
";",
"i",
"++",
")",
"{",
"textQuery",
"+=",
"(",
"i",
">",
"0",
"?",
"OPS",
"[",
"key",
"]",
":",
"''",
")",
"+",
"stringify",
"(",
"queryObject",
"[",
"i",
"]",
",",
"actualField",
")",
";",
"}",
"return",
"textQuery",
"+",
"')'",
";",
"}"
] | Converts logical operator queries into string by applying operator and
recursively invokes parsing process for rvalue.
@param {object} queryObject Which contains the operator.
@param {string} actualField Current field of the object which the filter is operating on.
@param {string} key Should be '$and' or '$or'. The current operation key.
@returns {string} | [
"Converts",
"logical",
"operator",
"queries",
"into",
"string",
"by",
"applying",
"operator",
"and",
"recursively",
"invokes",
"parsing",
"process",
"for",
"rvalue",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/query.js#L97-L105 | train |
tadam313/sheet-db | src/query.js | updateObject | function updateObject(entities, descriptor) {
if (!entities) {
return entities;
}
let result = Array.isArray(entities) ? entities : [entities];
if (!isUpdateDescriptor(descriptor)) {
return descriptor && typeof descriptor === 'object'
? [util.copyMetaProperties(descriptor, result[0])]
: result;
}
// get updater operations
let operations = Object.keys(descriptor)
.map(opType => ({name: opType, transformation: UPDATE_OPS[opType]}))
.filter(op => op.transformation);
for (let operator of operations) {
result = mutate(result, descriptor[operator.name], operator.transformation);
}
return result;
} | javascript | function updateObject(entities, descriptor) {
if (!entities) {
return entities;
}
let result = Array.isArray(entities) ? entities : [entities];
if (!isUpdateDescriptor(descriptor)) {
return descriptor && typeof descriptor === 'object'
? [util.copyMetaProperties(descriptor, result[0])]
: result;
}
// get updater operations
let operations = Object.keys(descriptor)
.map(opType => ({name: opType, transformation: UPDATE_OPS[opType]}))
.filter(op => op.transformation);
for (let operator of operations) {
result = mutate(result, descriptor[operator.name], operator.transformation);
}
return result;
} | [
"function",
"updateObject",
"(",
"entities",
",",
"descriptor",
")",
"{",
"if",
"(",
"!",
"entities",
")",
"{",
"return",
"entities",
";",
"}",
"let",
"result",
"=",
"Array",
".",
"isArray",
"(",
"entities",
")",
"?",
"entities",
":",
"[",
"entities",
"]",
";",
"if",
"(",
"!",
"isUpdateDescriptor",
"(",
"descriptor",
")",
")",
"{",
"return",
"descriptor",
"&&",
"typeof",
"descriptor",
"===",
"'object'",
"?",
"[",
"util",
".",
"copyMetaProperties",
"(",
"descriptor",
",",
"result",
"[",
"0",
"]",
")",
"]",
":",
"result",
";",
"}",
"let",
"operations",
"=",
"Object",
".",
"keys",
"(",
"descriptor",
")",
".",
"map",
"(",
"opType",
"=>",
"(",
"{",
"name",
":",
"opType",
",",
"transformation",
":",
"UPDATE_OPS",
"[",
"opType",
"]",
"}",
")",
")",
".",
"filter",
"(",
"op",
"=>",
"op",
".",
"transformation",
")",
";",
"for",
"(",
"let",
"operator",
"of",
"operations",
")",
"{",
"result",
"=",
"mutate",
"(",
"result",
",",
"descriptor",
"[",
"operator",
".",
"name",
"]",
",",
"operator",
".",
"transformation",
")",
";",
"}",
"return",
"result",
";",
"}"
] | Updates the object based on the MongoDB specification. It wont mutate the original object
@param {object} entities Original object
@param {object} descriptor Update description
@returns {*} | [
"Updates",
"the",
"object",
"based",
"on",
"the",
"MongoDB",
"specification",
".",
"It",
"wont",
"mutate",
"the",
"original",
"object"
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/query.js#L202-L226 | train |
tadam313/sheet-db | src/query.js | mutate | function mutate(entities, operationDescription, transformation) {
if (!operationDescription) {
return object;
}
return entities.map(item => {
Object.keys(operationDescription)
.forEach(key => transformation(item, key, operationDescription[key]));
return item;
});
} | javascript | function mutate(entities, operationDescription, transformation) {
if (!operationDescription) {
return object;
}
return entities.map(item => {
Object.keys(operationDescription)
.forEach(key => transformation(item, key, operationDescription[key]));
return item;
});
} | [
"function",
"mutate",
"(",
"entities",
",",
"operationDescription",
",",
"transformation",
")",
"{",
"if",
"(",
"!",
"operationDescription",
")",
"{",
"return",
"object",
";",
"}",
"return",
"entities",
".",
"map",
"(",
"item",
"=>",
"{",
"Object",
".",
"keys",
"(",
"operationDescription",
")",
".",
"forEach",
"(",
"key",
"=>",
"transformation",
"(",
"item",
",",
"key",
",",
"operationDescription",
"[",
"key",
"]",
")",
")",
";",
"return",
"item",
";",
"}",
")",
";",
"}"
] | Mutates the object according to the transform logic.
@param {object} entities Original entity object
@param {object} operationDescription Update descriptor
@param {function} transformation Transformator function
@returns {object} | [
"Mutates",
"the",
"object",
"according",
"to",
"the",
"transform",
"logic",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/query.js#L236-L247 | train |
tadam313/sheet-db | src/query.js | isUpdateDescriptor | function isUpdateDescriptor(descriptor) {
if (typeof descriptor !== 'object' || !descriptor) {
return false;
}
return Object.keys(descriptor).some(op => op in UPDATE_OPS);
} | javascript | function isUpdateDescriptor(descriptor) {
if (typeof descriptor !== 'object' || !descriptor) {
return false;
}
return Object.keys(descriptor).some(op => op in UPDATE_OPS);
} | [
"function",
"isUpdateDescriptor",
"(",
"descriptor",
")",
"{",
"if",
"(",
"typeof",
"descriptor",
"!==",
"'object'",
"||",
"!",
"descriptor",
")",
"{",
"return",
"false",
";",
"}",
"return",
"Object",
".",
"keys",
"(",
"descriptor",
")",
".",
"some",
"(",
"op",
"=>",
"op",
"in",
"UPDATE_OPS",
")",
";",
"}"
] | Checks whether the given object is Mongo update descriptor or not.
@param {*} descriptor Candidate descriptor being checked
@returns {boolean} | [
"Checks",
"whether",
"the",
"given",
"object",
"is",
"Mongo",
"update",
"descriptor",
"or",
"not",
"."
] | 2ca1b85b8a6086a327d65b98b68b543fade84848 | https://github.com/tadam313/sheet-db/blob/2ca1b85b8a6086a327d65b98b68b543fade84848/src/query.js#L255-L261 | train |
chip-js/fragments-js | src/template.js | function(doc) {
if (!doc) {
doc = document;
}
if (doc === document && this.pool.length) {
return this.pool.pop();
}
return View.makeInstanceOf(doc.importNode(this, true), this);
} | javascript | function(doc) {
if (!doc) {
doc = document;
}
if (doc === document && this.pool.length) {
return this.pool.pop();
}
return View.makeInstanceOf(doc.importNode(this, true), this);
} | [
"function",
"(",
"doc",
")",
"{",
"if",
"(",
"!",
"doc",
")",
"{",
"doc",
"=",
"document",
";",
"}",
"if",
"(",
"doc",
"===",
"document",
"&&",
"this",
".",
"pool",
".",
"length",
")",
"{",
"return",
"this",
".",
"pool",
".",
"pop",
"(",
")",
";",
"}",
"return",
"View",
".",
"makeInstanceOf",
"(",
"doc",
".",
"importNode",
"(",
"this",
",",
"true",
")",
",",
"this",
")",
";",
"}"
] | Creates a new view cloned from this template. | [
"Creates",
"a",
"new",
"view",
"cloned",
"from",
"this",
"template",
"."
] | 5d613ea42c3823423efb01fce4ffef80c7f5ce0f | https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/template.js#L25-L34 | train |
|
mikolalysenko/simplify-planar-graph | simplify.js | computeWeight | function computeWeight(i) {
if(dead[i]) {
return Infinity
}
//TODO: Check that the line segment doesn't cross once simplified
var s = inv[i]
var t = outv[i]
if((s<0) || (t<0)) {
return Infinity
} else {
return errorWeight(positions[i], positions[s], positions[t])
}
} | javascript | function computeWeight(i) {
if(dead[i]) {
return Infinity
}
//TODO: Check that the line segment doesn't cross once simplified
var s = inv[i]
var t = outv[i]
if((s<0) || (t<0)) {
return Infinity
} else {
return errorWeight(positions[i], positions[s], positions[t])
}
} | [
"function",
"computeWeight",
"(",
"i",
")",
"{",
"if",
"(",
"dead",
"[",
"i",
"]",
")",
"{",
"return",
"Infinity",
"}",
"var",
"s",
"=",
"inv",
"[",
"i",
"]",
"var",
"t",
"=",
"outv",
"[",
"i",
"]",
"if",
"(",
"(",
"s",
"<",
"0",
")",
"||",
"(",
"t",
"<",
"0",
")",
")",
"{",
"return",
"Infinity",
"}",
"else",
"{",
"return",
"errorWeight",
"(",
"positions",
"[",
"i",
"]",
",",
"positions",
"[",
"s",
"]",
",",
"positions",
"[",
"t",
"]",
")",
"}",
"}"
] | Updates the weight for vertex i | [
"Updates",
"the",
"weight",
"for",
"vertex",
"i"
] | 0338fdadf415f75205a43d8b34329d0553567879 | https://github.com/mikolalysenko/simplify-planar-graph/blob/0338fdadf415f75205a43d8b34329d0553567879/simplify.js#L51-L63 | train |
mikolalysenko/simplify-planar-graph | simplify.js | heapDown | function heapDown(i) {
var w = heapWeight(i)
while(true) {
var tw = w
var left = 2*i + 1
var right = 2*(i + 1)
var next = i
if(left < heapCount) {
var lw = heapWeight(left)
if(lw < tw) {
next = left
tw = lw
}
}
if(right < heapCount) {
var rw = heapWeight(right)
if(rw < tw) {
next = right
}
}
if(next === i) {
return i
}
heapSwap(i, next)
i = next
}
} | javascript | function heapDown(i) {
var w = heapWeight(i)
while(true) {
var tw = w
var left = 2*i + 1
var right = 2*(i + 1)
var next = i
if(left < heapCount) {
var lw = heapWeight(left)
if(lw < tw) {
next = left
tw = lw
}
}
if(right < heapCount) {
var rw = heapWeight(right)
if(rw < tw) {
next = right
}
}
if(next === i) {
return i
}
heapSwap(i, next)
i = next
}
} | [
"function",
"heapDown",
"(",
"i",
")",
"{",
"var",
"w",
"=",
"heapWeight",
"(",
"i",
")",
"while",
"(",
"true",
")",
"{",
"var",
"tw",
"=",
"w",
"var",
"left",
"=",
"2",
"*",
"i",
"+",
"1",
"var",
"right",
"=",
"2",
"*",
"(",
"i",
"+",
"1",
")",
"var",
"next",
"=",
"i",
"if",
"(",
"left",
"<",
"heapCount",
")",
"{",
"var",
"lw",
"=",
"heapWeight",
"(",
"left",
")",
"if",
"(",
"lw",
"<",
"tw",
")",
"{",
"next",
"=",
"left",
"tw",
"=",
"lw",
"}",
"}",
"if",
"(",
"right",
"<",
"heapCount",
")",
"{",
"var",
"rw",
"=",
"heapWeight",
"(",
"right",
")",
"if",
"(",
"rw",
"<",
"tw",
")",
"{",
"next",
"=",
"right",
"}",
"}",
"if",
"(",
"next",
"===",
"i",
")",
"{",
"return",
"i",
"}",
"heapSwap",
"(",
"i",
",",
"next",
")",
"i",
"=",
"next",
"}",
"}"
] | Bubble element i down the heap | [
"Bubble",
"element",
"i",
"down",
"the",
"heap"
] | 0338fdadf415f75205a43d8b34329d0553567879 | https://github.com/mikolalysenko/simplify-planar-graph/blob/0338fdadf415f75205a43d8b34329d0553567879/simplify.js#L88-L114 | train |
mikolalysenko/simplify-planar-graph | simplify.js | heapUp | function heapUp(i) {
var w = heapWeight(i)
while(i > 0) {
var parent = heapParent(i)
if(parent >= 0) {
var pw = heapWeight(parent)
if(w < pw) {
heapSwap(i, parent)
i = parent
continue
}
}
return i
}
} | javascript | function heapUp(i) {
var w = heapWeight(i)
while(i > 0) {
var parent = heapParent(i)
if(parent >= 0) {
var pw = heapWeight(parent)
if(w < pw) {
heapSwap(i, parent)
i = parent
continue
}
}
return i
}
} | [
"function",
"heapUp",
"(",
"i",
")",
"{",
"var",
"w",
"=",
"heapWeight",
"(",
"i",
")",
"while",
"(",
"i",
">",
"0",
")",
"{",
"var",
"parent",
"=",
"heapParent",
"(",
"i",
")",
"if",
"(",
"parent",
">=",
"0",
")",
"{",
"var",
"pw",
"=",
"heapWeight",
"(",
"parent",
")",
"if",
"(",
"w",
"<",
"pw",
")",
"{",
"heapSwap",
"(",
"i",
",",
"parent",
")",
"i",
"=",
"parent",
"continue",
"}",
"}",
"return",
"i",
"}",
"}"
] | Bubbles element i up the heap | [
"Bubbles",
"element",
"i",
"up",
"the",
"heap"
] | 0338fdadf415f75205a43d8b34329d0553567879 | https://github.com/mikolalysenko/simplify-planar-graph/blob/0338fdadf415f75205a43d8b34329d0553567879/simplify.js#L117-L131 | train |
mikolalysenko/simplify-planar-graph | simplify.js | heapUpdate | function heapUpdate(i, w) {
var a = heap[i]
if(weights[a] === w) {
return i
}
weights[a] = -Infinity
heapUp(i)
heapPop()
weights[a] = w
heapCount += 1
return heapUp(heapCount-1)
} | javascript | function heapUpdate(i, w) {
var a = heap[i]
if(weights[a] === w) {
return i
}
weights[a] = -Infinity
heapUp(i)
heapPop()
weights[a] = w
heapCount += 1
return heapUp(heapCount-1)
} | [
"function",
"heapUpdate",
"(",
"i",
",",
"w",
")",
"{",
"var",
"a",
"=",
"heap",
"[",
"i",
"]",
"if",
"(",
"weights",
"[",
"a",
"]",
"===",
"w",
")",
"{",
"return",
"i",
"}",
"weights",
"[",
"a",
"]",
"=",
"-",
"Infinity",
"heapUp",
"(",
"i",
")",
"heapPop",
"(",
")",
"weights",
"[",
"a",
"]",
"=",
"w",
"heapCount",
"+=",
"1",
"return",
"heapUp",
"(",
"heapCount",
"-",
"1",
")",
"}"
] | Update heap item i | [
"Update",
"heap",
"item",
"i"
] | 0338fdadf415f75205a43d8b34329d0553567879 | https://github.com/mikolalysenko/simplify-planar-graph/blob/0338fdadf415f75205a43d8b34329d0553567879/simplify.js#L146-L157 | train |
chip-js/fragments-js | src/util/animation.js | getComputedCSS | function getComputedCSS(styleName) {
if (this.ownerDocument.defaultView && this.ownerDocument.defaultView.opener) {
return this.ownerDocument.defaultView.getComputedStyle(this)[styleName];
}
return window.getComputedStyle(this)[styleName];
} | javascript | function getComputedCSS(styleName) {
if (this.ownerDocument.defaultView && this.ownerDocument.defaultView.opener) {
return this.ownerDocument.defaultView.getComputedStyle(this)[styleName];
}
return window.getComputedStyle(this)[styleName];
} | [
"function",
"getComputedCSS",
"(",
"styleName",
")",
"{",
"if",
"(",
"this",
".",
"ownerDocument",
".",
"defaultView",
"&&",
"this",
".",
"ownerDocument",
".",
"defaultView",
".",
"opener",
")",
"{",
"return",
"this",
".",
"ownerDocument",
".",
"defaultView",
".",
"getComputedStyle",
"(",
"this",
")",
"[",
"styleName",
"]",
";",
"}",
"return",
"window",
".",
"getComputedStyle",
"(",
"this",
")",
"[",
"styleName",
"]",
";",
"}"
] | Get the computed style on an element. | [
"Get",
"the",
"computed",
"style",
"on",
"an",
"element",
"."
] | 5d613ea42c3823423efb01fce4ffef80c7f5ce0f | https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/util/animation.js#L23-L28 | train |
chip-js/fragments-js | src/util/animation.js | animateElement | function animateElement(css, options) {
var playback = { onfinish: null };
if (!Array.isArray(css) || css.length !== 2 || !options || !options.hasOwnProperty('duration')) {
Promise.resolve().then(function() {
if (playback.onfinish) {
playback.onfinish();
}
});
return playback;
}
var element = this;
var duration = options.duration || 0;
var delay = options.delay || 0;
var easing = options.easing;
var initialCss = css[0];
var finalCss = css[1];
var allCss = {};
Object.keys(initialCss).forEach(function(key) {
allCss[key] = true;
element.style[key] = initialCss[key];
});
// trigger reflow
element.offsetWidth;
var transitionOptions = ' ' + duration + 'ms';
if (easing) {
transitionOptions += ' ' + easing;
}
if (delay) {
transitionOptions += ' ' + delay + 'ms';
}
element.style.transition = Object.keys(finalCss).map(function(key) {
return key + transitionOptions;
}).join(', ');
Object.keys(finalCss).forEach(function(key) {
allCss[key] = true;
element.style[key] = finalCss[key];
});
setTimeout(function() {
Object.keys(allCss).forEach(function(key) {
element.style[key] = '';
});
if (playback.onfinish) {
playback.onfinish();
}
}, duration + delay);
return playback;
} | javascript | function animateElement(css, options) {
var playback = { onfinish: null };
if (!Array.isArray(css) || css.length !== 2 || !options || !options.hasOwnProperty('duration')) {
Promise.resolve().then(function() {
if (playback.onfinish) {
playback.onfinish();
}
});
return playback;
}
var element = this;
var duration = options.duration || 0;
var delay = options.delay || 0;
var easing = options.easing;
var initialCss = css[0];
var finalCss = css[1];
var allCss = {};
Object.keys(initialCss).forEach(function(key) {
allCss[key] = true;
element.style[key] = initialCss[key];
});
// trigger reflow
element.offsetWidth;
var transitionOptions = ' ' + duration + 'ms';
if (easing) {
transitionOptions += ' ' + easing;
}
if (delay) {
transitionOptions += ' ' + delay + 'ms';
}
element.style.transition = Object.keys(finalCss).map(function(key) {
return key + transitionOptions;
}).join(', ');
Object.keys(finalCss).forEach(function(key) {
allCss[key] = true;
element.style[key] = finalCss[key];
});
setTimeout(function() {
Object.keys(allCss).forEach(function(key) {
element.style[key] = '';
});
if (playback.onfinish) {
playback.onfinish();
}
}, duration + delay);
return playback;
} | [
"function",
"animateElement",
"(",
"css",
",",
"options",
")",
"{",
"var",
"playback",
"=",
"{",
"onfinish",
":",
"null",
"}",
";",
"if",
"(",
"!",
"Array",
".",
"isArray",
"(",
"css",
")",
"||",
"css",
".",
"length",
"!==",
"2",
"||",
"!",
"options",
"||",
"!",
"options",
".",
"hasOwnProperty",
"(",
"'duration'",
")",
")",
"{",
"Promise",
".",
"resolve",
"(",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"playback",
".",
"onfinish",
")",
"{",
"playback",
".",
"onfinish",
"(",
")",
";",
"}",
"}",
")",
";",
"return",
"playback",
";",
"}",
"var",
"element",
"=",
"this",
";",
"var",
"duration",
"=",
"options",
".",
"duration",
"||",
"0",
";",
"var",
"delay",
"=",
"options",
".",
"delay",
"||",
"0",
";",
"var",
"easing",
"=",
"options",
".",
"easing",
";",
"var",
"initialCss",
"=",
"css",
"[",
"0",
"]",
";",
"var",
"finalCss",
"=",
"css",
"[",
"1",
"]",
";",
"var",
"allCss",
"=",
"{",
"}",
";",
"Object",
".",
"keys",
"(",
"initialCss",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"allCss",
"[",
"key",
"]",
"=",
"true",
";",
"element",
".",
"style",
"[",
"key",
"]",
"=",
"initialCss",
"[",
"key",
"]",
";",
"}",
")",
";",
"element",
".",
"offsetWidth",
";",
"var",
"transitionOptions",
"=",
"' '",
"+",
"duration",
"+",
"'ms'",
";",
"if",
"(",
"easing",
")",
"{",
"transitionOptions",
"+=",
"' '",
"+",
"easing",
";",
"}",
"if",
"(",
"delay",
")",
"{",
"transitionOptions",
"+=",
"' '",
"+",
"delay",
"+",
"'ms'",
";",
"}",
"element",
".",
"style",
".",
"transition",
"=",
"Object",
".",
"keys",
"(",
"finalCss",
")",
".",
"map",
"(",
"function",
"(",
"key",
")",
"{",
"return",
"key",
"+",
"transitionOptions",
";",
"}",
")",
".",
"join",
"(",
"', '",
")",
";",
"Object",
".",
"keys",
"(",
"finalCss",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"allCss",
"[",
"key",
"]",
"=",
"true",
";",
"element",
".",
"style",
"[",
"key",
"]",
"=",
"finalCss",
"[",
"key",
"]",
";",
"}",
")",
";",
"setTimeout",
"(",
"function",
"(",
")",
"{",
"Object",
".",
"keys",
"(",
"allCss",
")",
".",
"forEach",
"(",
"function",
"(",
"key",
")",
"{",
"element",
".",
"style",
"[",
"key",
"]",
"=",
"''",
";",
"}",
")",
";",
"if",
"(",
"playback",
".",
"onfinish",
")",
"{",
"playback",
".",
"onfinish",
"(",
")",
";",
"}",
"}",
",",
"duration",
"+",
"delay",
")",
";",
"return",
"playback",
";",
"}"
] | Very basic polyfill for Element.animate if it doesn't exist. If it does, use the native.
This only supports two css states. It will overwrite existing styles. It doesn't return an animation play control. It
only supports duration, delay, and easing. Returns an object with a property onfinish. | [
"Very",
"basic",
"polyfill",
"for",
"Element",
".",
"animate",
"if",
"it",
"doesn",
"t",
"exist",
".",
"If",
"it",
"does",
"use",
"the",
"native",
".",
"This",
"only",
"supports",
"two",
"css",
"states",
".",
"It",
"will",
"overwrite",
"existing",
"styles",
".",
"It",
"doesn",
"t",
"return",
"an",
"animation",
"play",
"control",
".",
"It",
"only",
"supports",
"duration",
"delay",
"and",
"easing",
".",
"Returns",
"an",
"object",
"with",
"a",
"property",
"onfinish",
"."
] | 5d613ea42c3823423efb01fce4ffef80c7f5ce0f | https://github.com/chip-js/fragments-js/blob/5d613ea42c3823423efb01fce4ffef80c7f5ce0f/src/util/animation.js#L35-L91 | train |
HaroldPutman/hubot-encourage | src/index.js | capitalize | function capitalize(str) {
let result = str.trim();
return result.substring(0, 1).toUpperCase() + result.substring(1);
} | javascript | function capitalize(str) {
let result = str.trim();
return result.substring(0, 1).toUpperCase() + result.substring(1);
} | [
"function",
"capitalize",
"(",
"str",
")",
"{",
"let",
"result",
"=",
"str",
".",
"trim",
"(",
")",
";",
"return",
"result",
".",
"substring",
"(",
"0",
",",
"1",
")",
".",
"toUpperCase",
"(",
")",
"+",
"result",
".",
"substring",
"(",
"1",
")",
";",
"}"
] | Capitalize the first letter in a string. | [
"Capitalize",
"the",
"first",
"letter",
"in",
"a",
"string",
"."
] | bf780dba2ad772d4f73f74e12c312686464a4990 | https://github.com/HaroldPutman/hubot-encourage/blob/bf780dba2ad772d4f73f74e12c312686464a4990/src/index.js#L41-L44 | train |
koggdal/matrixmath | arrays.js | getWithLength | function getWithLength(length) {
var arrays = pool[length];
var array;
var i;
// Create the first array for the specified length
if (!arrays) {
array = create(length);
}
// Find an unused array among the created arrays for the specified length
if (!array) {
for (i = arrays.length; i--;) {
if (!arrays[i].inUse) {
array = arrays[i];
break;
}
}
// If no array was found, create a new one
if (!array) {
array = create(length);
}
}
array.inUse = true;
return array;
} | javascript | function getWithLength(length) {
var arrays = pool[length];
var array;
var i;
// Create the first array for the specified length
if (!arrays) {
array = create(length);
}
// Find an unused array among the created arrays for the specified length
if (!array) {
for (i = arrays.length; i--;) {
if (!arrays[i].inUse) {
array = arrays[i];
break;
}
}
// If no array was found, create a new one
if (!array) {
array = create(length);
}
}
array.inUse = true;
return array;
} | [
"function",
"getWithLength",
"(",
"length",
")",
"{",
"var",
"arrays",
"=",
"pool",
"[",
"length",
"]",
";",
"var",
"array",
";",
"var",
"i",
";",
"if",
"(",
"!",
"arrays",
")",
"{",
"array",
"=",
"create",
"(",
"length",
")",
";",
"}",
"if",
"(",
"!",
"array",
")",
"{",
"for",
"(",
"i",
"=",
"arrays",
".",
"length",
";",
"i",
"--",
";",
")",
"{",
"if",
"(",
"!",
"arrays",
"[",
"i",
"]",
".",
"inUse",
")",
"{",
"array",
"=",
"arrays",
"[",
"i",
"]",
";",
"break",
";",
"}",
"}",
"if",
"(",
"!",
"array",
")",
"{",
"array",
"=",
"create",
"(",
"length",
")",
";",
"}",
"}",
"array",
".",
"inUse",
"=",
"true",
";",
"return",
"array",
";",
"}"
] | Get an array with the specified length from the pool.
@param {number} length The preferred length of the array.
@return {Array} An array. | [
"Get",
"an",
"array",
"with",
"the",
"specified",
"length",
"from",
"the",
"pool",
"."
] | 4bbc721be90149964bc80221f3afccc1c5f91953 | https://github.com/koggdal/matrixmath/blob/4bbc721be90149964bc80221f3afccc1c5f91953/arrays.js#L34-L61 | train |
koggdal/matrixmath | arrays.js | giveBack | function giveBack(array) {
// Don't return arrays that didn't originate from this pool
if (!array.hasOwnProperty('originalLength')) return;
// Reset all the elements
for (var i = array.length; i--;) {
array[i] = undefined;
}
// Reset the length
array.length = array.originalLength;
// Remove custom properties that the Matrix class might have added
delete array.rows;
delete array.cols;
// Let the pool know that it's no longer in use
array.inUse = false;
} | javascript | function giveBack(array) {
// Don't return arrays that didn't originate from this pool
if (!array.hasOwnProperty('originalLength')) return;
// Reset all the elements
for (var i = array.length; i--;) {
array[i] = undefined;
}
// Reset the length
array.length = array.originalLength;
// Remove custom properties that the Matrix class might have added
delete array.rows;
delete array.cols;
// Let the pool know that it's no longer in use
array.inUse = false;
} | [
"function",
"giveBack",
"(",
"array",
")",
"{",
"if",
"(",
"!",
"array",
".",
"hasOwnProperty",
"(",
"'originalLength'",
")",
")",
"return",
";",
"for",
"(",
"var",
"i",
"=",
"array",
".",
"length",
";",
"i",
"--",
";",
")",
"{",
"array",
"[",
"i",
"]",
"=",
"undefined",
";",
"}",
"array",
".",
"length",
"=",
"array",
".",
"originalLength",
";",
"delete",
"array",
".",
"rows",
";",
"delete",
"array",
".",
"cols",
";",
"array",
".",
"inUse",
"=",
"false",
";",
"}"
] | Give back an array to the pool.
This will reset the array to the original length and make all values
undefined.
@param {Array} array An array that was gotten from this pool before. | [
"Give",
"back",
"an",
"array",
"to",
"the",
"pool",
".",
"This",
"will",
"reset",
"the",
"array",
"to",
"the",
"original",
"length",
"and",
"make",
"all",
"values",
"undefined",
"."
] | 4bbc721be90149964bc80221f3afccc1c5f91953 | https://github.com/koggdal/matrixmath/blob/4bbc721be90149964bc80221f3afccc1c5f91953/arrays.js#L70-L89 | train |
koggdal/matrixmath | arrays.js | create | function create(length) {
var array = new Array(length);
// Create a non-enumerable property as a flag to know if the array is in use
Object.defineProperties(array, {
inUse: {
enumerable: false,
writable: true,
value: false
},
originalLength: {
enumerable: false,
value: length
}
});
if (!pool[length]) pool[length] = [];
pool[length].push(array);
return array;
} | javascript | function create(length) {
var array = new Array(length);
// Create a non-enumerable property as a flag to know if the array is in use
Object.defineProperties(array, {
inUse: {
enumerable: false,
writable: true,
value: false
},
originalLength: {
enumerable: false,
value: length
}
});
if (!pool[length]) pool[length] = [];
pool[length].push(array);
return array;
} | [
"function",
"create",
"(",
"length",
")",
"{",
"var",
"array",
"=",
"new",
"Array",
"(",
"length",
")",
";",
"Object",
".",
"defineProperties",
"(",
"array",
",",
"{",
"inUse",
":",
"{",
"enumerable",
":",
"false",
",",
"writable",
":",
"true",
",",
"value",
":",
"false",
"}",
",",
"originalLength",
":",
"{",
"enumerable",
":",
"false",
",",
"value",
":",
"length",
"}",
"}",
")",
";",
"if",
"(",
"!",
"pool",
"[",
"length",
"]",
")",
"pool",
"[",
"length",
"]",
"=",
"[",
"]",
";",
"pool",
"[",
"length",
"]",
".",
"push",
"(",
"array",
")",
";",
"return",
"array",
";",
"}"
] | Create a new array and add it to the pool for the specified length.
@param {number} length The length of the array to create.
@return {Array} The new array. | [
"Create",
"a",
"new",
"array",
"and",
"add",
"it",
"to",
"the",
"pool",
"for",
"the",
"specified",
"length",
"."
] | 4bbc721be90149964bc80221f3afccc1c5f91953 | https://github.com/koggdal/matrixmath/blob/4bbc721be90149964bc80221f3afccc1c5f91953/arrays.js#L98-L118 | train |
IonicaBizau/typpy | lib/index.js | Typpy | function Typpy(input, target) {
if (arguments.length === 2) {
return Typpy.is(input, target);
}
return Typpy.get(input, true);
} | javascript | function Typpy(input, target) {
if (arguments.length === 2) {
return Typpy.is(input, target);
}
return Typpy.get(input, true);
} | [
"function",
"Typpy",
"(",
"input",
",",
"target",
")",
"{",
"if",
"(",
"arguments",
".",
"length",
"===",
"2",
")",
"{",
"return",
"Typpy",
".",
"is",
"(",
"input",
",",
"target",
")",
";",
"}",
"return",
"Typpy",
".",
"get",
"(",
"input",
",",
"true",
")",
";",
"}"
] | Typpy
Gets the type of the input value or compares it
with a provided type.
Usage:
```js
Typpy({}) // => "object"
Typpy(42, Number); // => true
Typpy.get([], "array"); => true
```
@name Typpy
@function
@param {Anything} input The input value.
@param {Constructor|String} target The target type.
It could be a string (e.g. `"array"`) or a
constructor (e.g. `Array`).
@return {String|Boolean} It returns `true` if the
input has the provided type `target` (if was provided),
`false` if the input type does *not* have the provided type
`target` or the stringified type of the input (always lowercase). | [
"Typpy",
"Gets",
"the",
"type",
"of",
"the",
"input",
"value",
"or",
"compares",
"it",
"with",
"a",
"provided",
"type",
"."
] | 158e34a493cadc30e94cfd7dce8666f848fb31e7 | https://github.com/IonicaBizau/typpy/blob/158e34a493cadc30e94cfd7dce8666f848fb31e7/lib/index.js#L27-L32 | train |
sorensen/event-proxy | event-proxy.js | bind | function bind(scope, method) {
var args = slice.call(arguments, 2)
if (typeof method === 'string') {
method = scope[method]
}
if (!method) {
throw new Error('Proxy: method `' + method + '` does not exist')
}
return function() {
return method.apply(scope, concat.apply(args, arguments))
}
} | javascript | function bind(scope, method) {
var args = slice.call(arguments, 2)
if (typeof method === 'string') {
method = scope[method]
}
if (!method) {
throw new Error('Proxy: method `' + method + '` does not exist')
}
return function() {
return method.apply(scope, concat.apply(args, arguments))
}
} | [
"function",
"bind",
"(",
"scope",
",",
"method",
")",
"{",
"var",
"args",
"=",
"slice",
".",
"call",
"(",
"arguments",
",",
"2",
")",
"if",
"(",
"typeof",
"method",
"===",
"'string'",
")",
"{",
"method",
"=",
"scope",
"[",
"method",
"]",
"}",
"if",
"(",
"!",
"method",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Proxy: method `'",
"+",
"method",
"+",
"'` does not exist'",
")",
"}",
"return",
"function",
"(",
")",
"{",
"return",
"method",
".",
"apply",
"(",
"scope",
",",
"concat",
".",
"apply",
"(",
"args",
",",
"arguments",
")",
")",
"}",
"}"
] | Call a method of the given scope, prepending any given
args to the function call along with sent arguments
@param {Object} scope of method call
@param {String} method name
@param {...} additional arguments to be used every method call
@return {Object} js object
@api private | [
"Call",
"a",
"method",
"of",
"the",
"given",
"scope",
"prepending",
"any",
"given",
"args",
"to",
"the",
"function",
"call",
"along",
"with",
"sent",
"arguments"
] | 0e299607bb454b875b8d3102503285dde37ebd7a | https://github.com/sorensen/event-proxy/blob/0e299607bb454b875b8d3102503285dde37ebd7a/event-proxy.js#L43-L55 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.