Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplifying post ID generation #30

Open
oliverjam opened this issue Oct 1, 2021 · 0 comments
Open

Simplifying post ID generation #30

oliverjam opened this issue Oct 1, 2021 · 0 comments

Comments

@oliverjam
Copy link

let idArr = [];
let id = 0;
function post(request, response) {
const newPost = request.body;
if (newPost.post.length > 50) {
response.redirect('/add-post/error');
} else {
idArr = Object.keys(posts);
// eslint-disable-next-line radix
const idArrInt = idArr.map((el) => parseInt(el));
let bigId = idArrInt.reduce((acc, cur) => (acc > cur ? acc : cur), 0);
id = bigId + 1;
posts[id] = newPost;
response.redirect('/');
}
}

Unless I've misunderstood it seems like this code is there to ensure that you have sequentially increasing IDs. Each new ID you add should be one bigger than the previous biggest. It's clever code, and good use of higher-order array methods!

However I think it may be unnecessary—since you are keeping track of the ID in a variable outside the handler you will always have access to the previous ID, and so can just increment that each time. E.g.

let id = 0;

function post(request, response) {
  const newPost = request.body;
  id = id + 1;
  posts[id] = newPost;
  response.redirect('/');
}

The id variable will stick around for as long as your server is running and persist between POST requests, so you can rely on it always having the right value.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant