codecademy/lodash/_.js

71 lines
1.5 KiB
JavaScript
Raw Normal View History

2023-06-27 18:34:53 -07:00
const _ = {}
2023-06-27 18:13:07 -07:00
/* --------------------------------------------------------------- clamp ---- */
_.clamp = (num, lower, higher) => Math.min(Math.max(num, lower), higher)
2023-06-27 18:17:29 -07:00
/* ------------------------------------------------------------- inRange ---- */
_.inRange = function (num, start, end) {
if (!end) {
end = start
start = 0
}
if (start > end) {
2023-06-27 18:34:53 -07:00
const s = start
2023-06-27 18:17:29 -07:00
start = end
end = s
}
return start <= num && num < end
}
2023-06-27 18:19:28 -07:00
/* --------------------------------------------------------------- words ---- */
_.words = (string) => string.split(' ')
2023-06-27 18:34:53 -07:00
/* ----------------------------------------------------------------- pad ---- */
_.pad = function (string, length) {
if (string.length >= length) {
return string
}
const addToStart = Math.floor((length - string.length) / 2)
const addToEnd = length - string.length - addToStart
return ' '.repeat(addToStart) + string + ' '.repeat(addToEnd)
}
2023-06-27 18:39:00 -07:00
/* ----------------------------------------------------------------- has ---- */
2023-06-27 18:56:24 -07:00
_.has = (obj, key) => !!obj[key]
/* -------------------------------------------------------------- invert ---- */
_.invert = function (obj) {
const newObj = {}
for (const key in obj) {
newObj[obj[key]] = key
}
return newObj
2023-06-27 18:39:00 -07:00
}
2023-06-27 18:58:53 -07:00
/* ------------------------------------------------------------- findKey ---- */
_.findKey = function (obj, cb) {
for (const key in obj) {
if (cb(obj[key])) {
return key
}
}
return undefined
}
2023-06-27 18:12:38 -07:00
// Do not write or modify code below this line.
module.exports = _