Skip to content

Instantly share code, notes, and snippets.

@QuocCao-dev
Created September 24, 2022 08:23
Show Gist options
  • Save QuocCao-dev/21d29a01da3b742d9e8586e7fdc7bbbe to your computer and use it in GitHub Desktop.
Save QuocCao-dev/21d29a01da3b742d9e8586e7fdc7bbbe to your computer and use it in GitHub Desktop.
solutions
const subLength = (string, character) => {
let arr = []; // lưu index của 2 phần tử sẽ gặp
for (let i = 0; i < string.length; i++) {
if (string[i] === character) {
arr.push(i);
}
}
if (arr.length !== 2) return 0;
return arr[1] - arr[0] + 1;
};
function groceries(items) {
let result = "";
for (let i = 0; i < items.length; i++) {
if (i === items.length - 2) {
result += items[i].item + " and ";
} else if (i === items.length - 1) {
result += items[i].item;
} else {
result += items[i].item + ", ";
}
}
}
function groceries2(items) {
let itemsList = items.map((item) => item.item);
let lastItem = itemsList.pop();
return itemsList.length === 0
? lastItem
: itemsList.join(", ") + " and " + lastItem;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment